Class

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.

Overview

Anchored object queries provide an easy way to search for new data in the HealthKit store. An HKAnchoredObjectQuery 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 updateHandler 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.

// Create the step count type.
guard let stepCountType = HKObjectType.quantityType(forIdentifier: .stepCount) else {
    // This should never fail when using a defined constant.
    fatalError("*** Unable to get the step count type ***")
}

// Create the query.
let query = HKAnchoredObjectQuery(type: stepCountType,
                                  predicate: nil,
                                  anchor: myAnchor,
                                  limit: HKObjectQueryNoLimit)
{ (query, samplesOrNil, deletedObjectsOrNil, newAnchor, errorOrNil) in
    
    guard let samples = samplesOrNil, let deletedObjects = deletedObjectsOrNil else {
        // Handle the error here.
        fatalError("*** An error occurred during the initial query: \(errorOrNil!.localizedDescription) ***")
    }
    
    myAnchor = newAnchor
    
    for stepCountSample in samples {
        // Process the new step count samples here.
    }
    
    for deletedStepCountSamples in deletedObjects {
        // Process the deleted step count samples here.
    }
}

// Optionally, add an update handler.
query.updateHandler = { (query, samplesOrNil, deletedObjectsOrNil, newAnchor, errorOrNil) in
    
    guard let samples = samplesOrNil, let deletedObjects = deletedObjectsOrNil else {
        // Handle the error here.
        fatalError("*** An error occurred during an update: \(errorOrNil!.localizedDescription) ***")
    }
    
    myAnchor = newAnchor
    
    for stepCountSample in samples {
        // Process the step counts from the update here.
    }
    
    for deletedStepCountSamples in deletedObjects {
        // Process the deleted step count samples from the update here.
    }
}

// Run the query.
store.execute(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.

If the myAnchor 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 HKSampleQuery), with the ability to perform a long-running query that responds to updates (like an HKObserverQuery).

Often, it is more efficient to setup and run a single anchored object query, then 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 nil.

Topics

Tracking Anchors

class HKQueryAnchor

An object used to identify all the samples previously returned by an anchored object query.

Tracking Deleted Objects

class HKDeletedObject

An object that represents a sample that has been deleted from the HealthKit store.

Relationships

Inherits From

Conforms To

See Also

Common Query Types

class HKSampleQuery

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

class HKQuantitySeriesSampleQuery

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

class HKObserverQuery

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.

class HKCorrelationQuery

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

class HKDocumentQuery

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

class HKQuery

An abstract class for all the query classes in HealthKit.