YoungLion
YoungLion

Reputation: 11

How to use HealthKit background delivery?

What is the correct way to use background delivery in iOS 8 HealthKit?

The following is my code to enable HealthKit background delivery.

- (void)observeSleepData {
    HKCategoryType *sleepType = [HKCategoryType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
    [self.healthStore enableBackgroundDeliveryForType:sleepType frequency:HKUpdateFrequencyImmediate withCompletion:^(BOOL success, NSError *error) {
        if (success) {

        }
    }];
    HKObserverQuery *query = [[HKObserverQuery alloc] initWithSampleType:sleepType predicate:nil updateHandler:^(HKObserverQuery *query, HKObserverQueryCompletionHandler completionHandler, NSError *error) {
        NSLog(@"sleep data updated");
    }];
    [self.healthStore executeQuery:query];
}

Do I need to configure extra things to make this work other than enabling HealthKit capability? Does HKObserverQuery respond to manual input in iOS8 native Health app?

Upvotes: 1

Views: 4361

Answers (2)

Maxwell
Maxwell

Reputation: 91

The HealthKit API Reference says:

The HealthKit data is only kept locally on the user’s device. For security, the HealthKit store is encrypted when the device is locked. The HealthKit store can only be accessed by an authorized app. As a result, you may not be able to read data from the store when your app is launched in the background; however, apps can still write data to the store, even when the phone is locked. HealthKit temporarily caches the data and saves it to the encrypted store as soon as the phone is unlocked

Upvotes: 2

drdaanger
drdaanger

Reputation: 360

From my own limited testing, a response from HKObserverQuery only means something changed in the data type you specified. It doesn't tell you what changed or come back with new data. Your code above should work, as long as you put an actual query (likely an anchored query) in the if (success) {} block.

I've gotten code similar to this to run when I update the native Health app.

EDIT:

I gave a more complete answer here: https://stackoverflow.com/a/26385281/1563787

Upvotes: 2

Related Questions