A long-running query that monitors the HealthKit store and updates your app whenever a matching sample is saved to or deleted from the HealthKit store.
- iOS 8.0+
- watchOS 2.0+
Observer queries set up a long-running task on a background queue. This task watches the HealthKit store, and alerts you whenever matching data is saved to or removed from the store. Observer queries let your app respond to changes made by other apps and devices.
Observer queries are immutable: Their properties are set when they are first created, and they cannot change.
Using Observer Queries
You create an observer query by calling the
init(sample initializer. After the query is instantiated, you run it by calling the HealthKit store’s
execute(_:) 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
The sample code in Listing 1 builds an observer query that responds to changes to the user’s step count.
Listing 1creates an observer query that receives updates whenever 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 whenever any step count data is saved to or deleted 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 the update handler block is defined, the query is complete. The sample code simply executes this 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
enable method. This method registers your app for background notifications. HealthKit wakes your app whenever new samples of the specified type are saved to the store. Your app is called 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(_: method. By setting up the queries in
application(_:, 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
For more information on the background delivery completion handler, see