HealthKit 不是最新的

HealthKit not up to date

我在我的一个应用程序中使用 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];
        }
    }];
}

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

看起来 HealthKit 只定期从 CoreMotion 导入步数信息,因此您会看到延迟。为我添加回调没有用,因为它似乎只在步骤数据导入 HealthKit 后才会回调