Sergio Prado
Sergio Prado

Reputation: 1216

HealthKit: HKObserverQuery not Firing

I'm trying to do a pretty basic thing: set up an HKObserverQuery so I can know when various data points are changed (I've made sure that the user has authorized the app to use the data point in question.) For whatever reason, I can get the query to fire every time the app is launched, but it does not fire when I close the app, go into the Health app, and manually update the data point. I've done a fair amount of searching and haven't been able to successfully use the code that others have posted, code that they say works for them.

I'm two weeks into Cocoa/Objective C development, so I'm sure I'm missing something obvious, but I can't see what it is. Any guidance here would be great, even if it's just advice on debugging. Since the app itself is closed and I'm not getting anything that it might log out in the console, I don't really have any visibility into what's happening.

The code that I'm using for the observer query is below:

   HKQuantityType *heartRate = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
    [self.healthStore enableBackgroundDeliveryForType:heartRate frequency:HKUpdateFrequencyImmediate withCompletion:^(BOOL success, NSError *error) {
        if (success) {
            NSLog(@"observing heart rate");
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.bodbot.com/Scripts/wearable_heartrate_changed.php"]];
        }else{
            NSLog(@"FAILED observing heart rate");
        }
    }];
    HKObserverQuery *query = [[HKObserverQuery alloc] initWithSampleType:heartRate predicate:nil updateHandler:^(HKObserverQuery *query, HKObserverQueryCompletionHandler completionHandler, NSError *error) {
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.bodbot.com/Scripts/wearable_heartrate_changed.php"]];
    }];

    [self.healthStore executeQuery:query];

Thanks!

Upvotes: 1

Views: 2407

Answers (2)

Allan
Allan

Reputation: 7363

When you suspend an app on iOS, by default it stops running unless it has taken a background task assertion or has a background mode entitlement. The app cannot receive notifications when it is not running. HealthKit has a feature which can wake your app in the background when there are new samples of a particular type, though. See the Managing Background Delivery documentation for HKHealthStore. Use that in conjunction with HKObserverQuery to be notified whenever there is new data, even when your app is not already running.

Upvotes: -1

steve1951
steve1951

Reputation: 193

I have found, empirically (not from documentation), that the Observer Query does NOT fire when running in the simulator but it DOES fire when running on device. And I do not have the background modes capability turned on.

Upvotes: 3

Related Questions