【问题标题】:HealthKit cannot read steps dataHealthKit 无法读取步数数据
【发布时间】:2016-04-04 09:00:25
【问题描述】:

我正在使用 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 上构建并运行代码,在设置 -> 隐私 -> 健康中,确实允许该应用读取数据,但日志区域仅显示:

steps:0.000000

我在 for 循环和 NSLog(@"error:%@", error) 上设置了一个断点,但应用程序没有中断。

有人可以帮忙吗?

【问题讨论】:

  • 你没有检查错误参数?你通过results: %lu日志吗?我不确定那是你应该stopQuery: 的地方。看起来很奇怪。
  • @Larme 我还检查了error,但NSLog(@"error:%@", error) 没有记录任何内容。

标签: ios objective-c healthkit hksamplequery


【解决方案1】:

试试这个代码,你只需更改开始日期和结束日期。

-(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];
}

【讨论】:

    【解决方案2】:

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

    第二个问题是您的代码过早地尝试记录步数。查询异步运行,一旦查询完成,resultsHandler 将在后台线程上调用。我建议在块内记录stepsCount。

    最后,如果您想计算用户的步数,您应该使用HKStatisticsQuery,而不是对HKSampleQuery 的结果求和。 HKStatisticsQuery 效率更高,并且在 HealthKit 中有多个重叠数据源时会产生正确的结果。例如,如果用户同时拥有 iPhone 和 Apple Watch,则您当前的实现将计算用户的步数。

    【讨论】:

    • 它有效,感谢您的回答和建议!我把HKSampleQuery改成了HKStatisticsQuery,确实效率更高了,但是不能实时更新步数,只有打开Health应用才会更新查询结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    相关资源
    最近更新 更多