Class

HKObserverQuery

A long-running query that monitors the HealthKit store and updates your app when the HealthKit store saves or deletes a matching sample.

Declaration

@interface HKObserverQuery : HKQuery

Overview

Observer queries set up a long-running task on a background queue. This task watches the HealthKit store, and alerts you when the store saves or removes matching data. Your app uses observer queries to respond to changes made by other apps and devices.

Observer queries are immutable: You set their properties when you first create them, and you can’t change them.

Using Observer Queries

You create an observer query by calling the initWithSampleType:predicate:updateHandler: initializer. After the query is instantiated, you run it by calling the HealthKit store’s executeQuery: method. Observer queries are long-running tasks. They continue to run on an anonymous background thread, calling their results handler whenever data matching the query changes. To stop the query, call the HealthKit store’s stopQuery: method.

The sample code in Listing 1 builds an observer query that responds to changes to the user’s step count.

Listing 1

Watching for updates

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);
         abort();
     }
 
     // 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];

Listing 1 creates an observer query that receives updates when HealthKit’s step count data changes. It starts by creating a sample type for the step count, then it creates the query itself. To ensure that this query receives updates when the system or any app saves or deletes step count data from the store, the sample passes in a nil predicate. Then, in the update handler, the sample code checks for errors. If no errors are found, it updates the daily step counts.

After defining the update handler block, the sample code executes the query using the HealthKit store.

Receiving Background Deliveries

Apps can also register to receive updates while in the background by calling the HealthKit store’s enableBackgroundDeliveryForType:frequency:withCompletion: method. This method registers your app for background notifications. HealthKit wakes your app when the store receives new samples of the specified type. HealthKit notifies your app at most once per time period defined by the frequency you specified when registering.

As soon as your app launches, HealthKit calls the update handler for any observer queries that match the newly saved data. If you plan on supporting background delivery, set up all your observer queries in your app delegate’s application:didFinishLaunchingWithOptions: method. By setting up the queries in application:didFinishLaunchingWithOptions:, you ensure that the queries are instantiated and ready to use before HealthKit delivers the updates.

After your observer queries have finished processing the new data, you must call the update’s completion handler. This lets HealthKit know that you have successfully received the background delivery.

For more information on managing background deliveries, see Managing Background Deliveries in HKHealthStore.

For more information on the background delivery completion handler, see HKObserverQueryCompletionHandler.

Topics

Creating Observer Queries

- initWithSampleType:predicate:updateHandler:

Instantiates and returns a query that monitors the HealthKit store and responds to changes.

HKObserverQueryCompletionHandler

The completion handler for background deliveries.

Constants

HKObserverQueryCompletionHandler

The completion handler for background deliveries.

Relationships

Inherits From

See Also

Common Query Types

HKSampleQuery

A general-purpose query that returns a snapshot of all the matching samples currently saved in the HealthKit store.

HKQuantitySeriesSampleQuery

A query that accesses the series data associated with a quantity sample.

HKAnchoredObjectQuery

A query that returns only recent changes to the HealthKit store, including a snapshot of new changes and continuous monitoring as a long-running query.

HKCorrelationQuery

A query that performs complex searches based on the correlation’s contents, and returns a snapshot of all matching samples.

HKDocumentQuery

A query that returns a snapshot of all matching documents currently saved in the HealthKit store.

HKHeartbeatSeriesQuery

A query that returns the heartbeat data contained in a heartbeat series sample.

HKQuery

An abstract class for all the query classes in HealthKit.