4

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

1 回答 1

3

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

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

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

于 2015-03-12T03:56:19.760 回答