在運(yùn)動(dòng)型或者健康管理類的項(xiàng)目當(dāng)中HeathKit是必不可少的他可以獲取到用戶的健康數(shù)據(jù)
iOS8以后蘋果系統(tǒng)增加了健康手,開發(fā)者可以利用HealthKit獲取到系統(tǒng)的步數(shù)信息
1. 要獲取到用戶的權(quán)限,經(jīng)過(guò)用戶同意之后才能獲取到健康數(shù)據(jù)

if (![HKHealthStore isHealthDataAvailable]) {
NSLog(@"不支持獲取步數(shù)");
}
self.healthStore = [[HKHealthStore alloc] init];
//設(shè)置需要獲取的權(quán)限
HKObjectType *objectType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSet *healthSet = [NSSet setWithObjects:objectType,nil];
[self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
if (success) {
//獲取步數(shù)的方法接下來(lái)去實(shí)現(xiàn)這個(gè)方法
[self readStepCount];
}
}];
2. #pragma mark -- /*獲取步數(shù)方法*/
- (void)readStepCount {
HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
//獲取當(dāng)前的時(shí)間進(jìn)行對(duì)比
NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents * dateComponents = [calendar components:unitFlags fromDate:date];
int hour = (int)dateComponents.hour;
int minute = (int)dateComponents.minute;
int second = (int)dateComponents.second;
NSDate *nowDay = [NSDate dateWithTimeIntervalSinceNow:-(hour *3600 + minute * 360 + second)];
NSLog(@"今天%@",nowDay);
NSDate *nextDay = [NSDate dateWithTimeIntervalSinceNow:- (hour *3600 + minute * 360 + second) + 86400];
NSLog(@"明天%@",nextDay);
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:nowDay endDate:nextDay options:HKQueryOptionNone];
HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:predicate limit:0 sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
int allStepCount = 0;
for (int i = 0; i < results.count ; i++) {
HKQuantitySample *result = results[i];
HKQuantity *quantity = result.quantity;
NSMutableString *mutableString = (NSMutableString *)quantity;
NSString *step = [NSString stringWithFormat:@"%@",mutableString];
//獲取51 count此類字符串前面的數(shù)字
NSString *str = [step componentsSeparatedByString:@" "][0];
int stepNum = [str intValue];
NSLog(@"%d",stepNum);
//把一天中所有時(shí)間段中的步數(shù)加到一起
allStepCount = allStepCount + stepNum;
}
self.countLabel.text = [NSString stringWithFormat:@"你今天走了%d",allStepCount];
}];
[self.healthStore executeQuery:sampleQuery];
}