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.
- iOS 8.0+
- Mac Catalyst 13.0+
- watchOS 2.0+
Anchored object queries provide an easy way to search for new data in the HealthKit store. An
HKAnchored returns an anchor value that corresponds to the last sample or deleted object received by that query. Subsequent queries can use this anchor to restrict their results to only newer saved or deleted objects.
Anchored object queries are mostly immutable. You can assign the query’s
update property after instantiating the object. All other properties must be set when you instantiate the object, and they cannot change.
Running Anchored Object Queries
The following sample code builds and executes an anchored object query.
Because this example queries for all step count samples, it does not use a predicate or limit to filter the results. Also, by setting the update handler, it requests all matching samples currently in the HealthKit store, along with any matching updates to the store.
For the current samples, HealthKit calls the result handler after completing the initial query.
For updates, the query continues to run and monitor the HealthKit store after completing the initial query. HealthKit calls the update handler whenever it detects a change to the affected objects.
my property is set to
nil, the query returns all the step count data currently available in the HealthKit store. On subsequent runs, the code uses the anchor returned by the previous query. These queries return only the step count samples that have been saved or deleted since the previous run.
Combining Snapshots and Updates
The anchored object query combines the ability to grab a snapshot of the data currently stored in HealthKit (like an
HKSample) with the ability to perform a long-running query that responds to updates (like an
Often, it is more efficient to set up and run a single anchored object query than to run separate sample and observer queries. As a result, you may want to use anchored object queries, even when you aren't using anchors to limit the results. In this case, simply set the anchor parameter to