I wrote a code to get heart rate values from Health kit. The code is working fine but when the new heart values are updated in Health kit. I have to come to main screen and then
See if the following code could help you...
HKSampleType *sampleType =
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
HKObserverQuery *query =
[[HKObserverQuery alloc]
initWithSampleType:sampleType
predicate:nil
updateHandler:^(HKObserverQuery *query,
HKObserverQueryCompletionHandler completionHandler,
NSError *error) {
if (error) {
NSLog(@"error occured while setting observer. %@ ",
error.localizedDescription);
abort();
}
// Take whatever steps are necessary to update your app's data and UI
// This may involve executing other queries
[self executeAnchoredQuery];
// If you have subscribed for background updates you must call the completion handler here.
// completionHandler();
}];
[self.healthStore executeQuery:query];
and then the function where you write you anchoredQuery code, this may give you an idea of the code flow :
-(void)executeAnchoredQuery
{
HKSampleType *sampleType =
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKAnchoredObjectQuery *query =
[[HKAnchoredObjectQuery alloc]
initWithType:sampleType
predicate:nil
anchor:self.anchor
limit:HKObjectQueryNoLimit
resultsHandler:^(HKAnchoredObjectQuery * _Nonnull query,
NSArray<__kindof HKSample *> * _Nullable sampleObjects,
NSArray<HKDeletedObject *> * _Nullable deletedObjects,
HKQueryAnchor * _Nullable newAnchor,
NSError * _Nullable error) {
if (error != nil) {
// Add proper error handling here...
NSLog(@"*** Unable to query for step counts: %@ ***",
error.localizedDescription);
abort();
}
// Process the results...
self.anchor = newAnchor;
for (HKQuantitySample *sample in sampleObjects) {
[self addStepCountSample:sample];
}
for (HKDeletedObject *sample in deletedObjects) {
[self removeStepCountSample:sample];
}
NSLog(@"Done!");
}];
[self.healthStore executeQuery:query];
}
Please go through apple developer docs for further details.