1

我正在使用 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),但应用程序没有中断。

有人可以帮忙吗?

4

2 回答 2

2

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

-(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];
}
于 2016-09-15T11:18:42.363 回答
1

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

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

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

于 2016-04-05T19:56:57.060 回答