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