问题
I'm using HealthKit in one of my apps
I may be using it wrong, but I have found that when reading steps (I haven't tried with other data), new step data isn't returned in my query and I need to open the Health app, and then open my app for that new information to be returned by the query.
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:
I found the same thing too - check out the following SO answer
https://stackoverflow.com/a/27239738/3847
Looks like HealthKit only imports the step information from CoreMotion periodically, hence the delay you're seeing. Adding the callback for me didn't work as it only seems to callback once the step data is imported into HealthKit
来源:https://stackoverflow.com/questions/28100936/healthkit-not-up-to-date