Let's say we're using step count as the trigger- if the user takes 10 steps, I want a notification to pop up saying so.
This question has been answered here: Healthkit background delivery when app is not running
However, I haven't been able to get it to work. If I walk around with the app in the foreground the step count will get updated. If I leave the app in the background the step count only seems to be updated after I reopen the app. So the background query doesn't seem to be working.
I've tried enabling Background Modes, no effect; I've tried leaving the app in the background for several hours thinking it might take a while for the data to be sent- nothing.
Someone elsewhere was saying to try StatisticsCollectionQuery because StatisticsQuery was broken- any truth to that? StatisticsCollectionQuery is not really ideal for what I'm doing.
Here's my query code:
[self.healthStore enableBackgroundDeliveryForType:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]
frequency:HKUpdateFrequencyImmediate
withCompletion:^(BOOL success, NSError * _Nullable error) {
if (error) {
// Perform Proper Error Handling Here...
NSLog(@"*** An error occured while setting up background updates. %@ ***",
error.localizedDescription);
}
if (success == YES) {
backgroundEnabled = YES;
}
}];
// set up running observer
HKSampleType *sampleType =
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKObserverQuery *query =
[[HKObserverQuery alloc]
initWithSampleType:sampleType
predicate:nil
updateHandler:^(HKObserverQuery *query,
HKObserverQueryCompletionHandler completionHandler,
NSError *error) {
if (error) {
// Perform Proper Error Handling Here...
NSLog(@"*** An error occured while setting up the stepCount observer. %@ ***",
error.localizedDescription);
// Error popup
return;
}
// Take whatever steps are necessary to update your app's data and UI
// This may involve executing other queries
[self updateDailyStepCount];
// If you have subscribed for background updates you must call the completion handler here.
completionHandler();
}];
[self.healthStore executeQuery:query];