HealthKit无法读取步骤数据

我正在使用HealthKit从我的iOS设备读取步骤数据。

这里是我的代码:

if ([HKHealthStore isHealthDataAvailable]) { __block double stepsCount = 0.0; self.healthStore = [[HKHealthStore alloc] init]; NSSet *stepsType =[NSSet setWithObject:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]]; [self.healthStore requestAuthorizationToShareTypes:nil readTypes:stepsType completion:^(BOOL success, NSError * _Nullable error) { if (success) { HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:nil limit:HKObjectQueryNoLimit sortDescriptors:nil resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) { if (error != nil) { NSLog(@"results: %lu", (unsigned long)[results count]); for (HKQuantitySample *result in results) { stepsCount += [result.quantity doubleValueForUnit:[HKUnit countUnit]]; } NSLog(@"Steps Count: %f", stepsCount); } else { NSLog(@"error:%@", error); }]; [self.healthStore executeQuery:sampleQuery]; [self.healthStore stopQuery:sampleQuery]; NSLog(@"steps:%f",stepsCount); } }]; } 

我在iPhone6上构build并运行代码,该代码具有步骤数据,在设置 – >隐私 – >运行状况下,应用程序已被允许读取数据,但日志区域仅显示:

 steps:0.000000 

我在for循环和NSLog(@"error:%@", error)上放了一个断点,但是应用程序不会中断。

任何人都可以帮忙?

您的代码会在有机会运行之前立即停止查询。 对于这个查询,没有理由调用stopQuery:除非要在查询完成之前取消查询。 由于查询不是很长时间(它没有updateHandler ),它将在调用resultsHandler之后立即停止。

第二个问题是您的代码尝试logging步骤计数太快。 查询asynchronous运行,一旦查询完成, resultsHandler将在后台线程上调用。 我build议在块内loggingstepsCount

最后,如果要计算用户的步骤,则应该使用HKStatisticsQuery而不是HKStatisticsQuery的结果。 HKStatisticsQuery中存在多个重叠数据源时, HKStatisticsQuery更高效,并且会产生正确的结果。 例如,如果您的iPhone和Apple Watch具有iPhone和Apple Watch,那么您当前的实施将重复计算用户的步骤。

试试这个代码,只是改变开始date和结束date。

 -(void) getQuantityResult { NSInteger limit = 0; NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:currentDate endDate:[[NSDate date]dateByAddingTimeInterval:60*60*24*3] options:HKQueryOptionStrictStartDate]; NSString *endKey = HKSampleSortIdentifierEndDate; NSSortDescriptor *endDate = [NSSortDescriptor sortDescriptorWithKey: endKey ascending: NO]; HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount] predicate: predicate limit: limit sortDescriptors: @[endDate] resultsHandler:^(HKSampleQuery *query, NSArray* results, NSError *error){ dispatch_async(dispatch_get_main_queue(), ^{ // sends the data using HTTP int dailyAVG = 0; for(HKQuantitySample *samples in results) { dailyAVG += [[samples quantity] doubleValueForUnit:[HKUnit countUnit]]; } lblPrint.text = [NSString stringWithFormat:@"%d",dailyAVG]; NSLog(@"%@",lblPrint.text); NSLog(@"%@",@"Done"); }); }]; [self.healthStore executeQuery:query]; }