HealthKit不是最新的

时间:2015-01-23 00:07:09

标签: ios health-kit

我在我的某个应用中使用HealthKit

我可能使用它错了,但我发现在阅读步骤时(我还没有尝试过其他数据),我的查询中没有返回新的步骤数据,我需要打开健康状况应用程序,然后打开我的应用程序以查询要返回的新信息。

if([HKHealthStore isHealthDataAvailable])
{
    HKHealthStore *healthStore = [[HKHealthStore alloc] init];

    //  Query for step data
    HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    NSSet *set = [NSSet setWithArray:@[stepType]];

    [healthStore requestAuthorizationToShareTypes:nil readTypes:set completion:^(BOOL success, NSError *error) {

        if(success)
        {
            //  Steps in 30 minute increments
            NSDateComponents *intervalComponents = [[NSDateComponents alloc] init];
            [intervalComponents setMinute:30];

            NSCalendar *calendar = [NSCalendar currentCalendar];

            NSDate *now = [NSDate date];

            NSDate *startDate = [calendar startOfDayForDate:now];
            NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];

            //  From the start of today until the end of today
            NSPredicate *datePredicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:(HKQueryOptionStrictStartDate | HKQueryOptionStrictEndDate)];

            HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:stepType
                                                                                   quantitySamplePredicate:datePredicate
                                                                                                   options:(HKStatisticsOptionCumulativeSum)
                                                                                                anchorDate:startDate
                                                                                        intervalComponents:intervalComponents];

            [query setInitialResultsHandler:^(HKStatisticsCollectionQuery *query, HKStatisticsCollection *result, NSError *error) {

                for(HKStatistics *statistics in result.statistics)
                {
                    NSLog(@"%@, %@", @([statistics.sumQuantity doubleValueForUnit:[HKUnit countUnit]]), statistics.startDate);
                }
            }];

            [healthStore executeQuery:query];
        }
    }];
}

1 个答案:

答案 0 :(得分:3)

我也发现了同样的事情 - 请查看以下SO答案

https://stackoverflow.com/a/27239738/3847

看起来HealthKit只会定期从CoreMotion导入步骤信息,因此您会看到延迟。为我添加回调不起作用,因为一旦将步骤数据导入HealthKit它似乎只回调