I have an issue I'm trying to solve, I've setup an HKObserveryQuery
, which works great and gathers new data for me.
The issue however is that sometimes when I go back to the Health app and delete an item after I've manually added it to the Health app, I notice the HKObserverQuery
I've set up fires two times very closely together, which I'm trying to solve because I use this observer to later upload some data, and I don't want a duplicate.
I'd appreciate any help offered. Code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self setup];
return YES;
}
- (void)setup
{
if ([HKHealthStore isHealthDataAvailable])
{
self.healthStore = [[HKHealthStore alloc]init];
NSSet *readTypes = [NSSet setWithObject:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate]];
[self.healthStore requestAuthorizationToShareTypes:nil
readTypes:readTypes
completion:^(BOOL success, NSError *error)
{
if (!error && success)
{
[self observeHR];
[self.healthStore enableBackgroundDeliveryForType:
[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate]
frequency:HKUpdateFrequencyImmediate withCompletion:^(BOOL success, NSError *error){}];
}
}];
}
}
- (void)observeHR
{
HKObserverQuery *query = [[HKObserverQuery alloc]initWithSampleType:[HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate]
predicate:nil
updateHandler:^(HKObserverQuery *query, HKObserverQueryCompletionHandler completionHandler, NSError *error)
{
if (!error)
{
// Randomly called twice *VERY* close together
NSLog(@"Query");
[self queryWithCompletionHandler:completionHandler];
}
else
{
if (completionHandler)
{
completionHandler();
}
}
}];
[self.healthStore executeQuery:query];
}
Console output, notice the times: This occurs when only deleting one item from the Health app, which is incorrect.
2014-12-29 16:50:20.121 TestApp[174:5674] Query
2014-12-29 16:50:20.124 TestApp[174:5674] Query