init(type:predicate:anchor:limit:completionHandler:)
Initializes a new anchored object query.
Declaration
init(type: HKSampleType, predicate: NSPredicate?, anchor: Int, limit: Int, completionHandler handler: @escaping @Sendable (HKAnchoredObjectQuery, [HKSample]?, Int, (any Error)?) -> Void)Parameters
- type:
The type of sample to search for. This query supports all sample types. Specifically, you can pass any concrete subclass of the Hksampletype class (the Hkquantitytype, Hkcategorytype, Hkworkouttype, and Hkcorrelationtype classes).
- predicate:
A predicate that filters the samples returned by the query. Pass
nilto receive all the new samples of the specified type. - anchor:
The anchor returned by the previous anchored object query. The anchor value corresponds to the last sample that was returned by the previous anchored object query. The new query returns only objects newer than that sample.
- limit:
The maximum number of samples received by the query. To receive all of the new samples, pass Hkobjectquerynolimit.
- handler:
A block that is called when the query finishes executing. This block takes the following parameters:
- query
A reference to the query calling this block.
- results
An array containing the samples returned by this query, or
nilif an error occurred.- newAnchor
A value corresponding to the last sample in the results array. Subsequent anchor queries can use this value to receive only the samples that have been saved and the objects that have been deleted since this query completed.
- error
If an error occurs, this parameter contains an object describing the error; otherwise, it is
nil.
Return Value
A newly initialized anchor query object.
Discussion
After instantiating the query, call the HKHealthStore class’s execute(_:) method to run it. The queries run on an anonymous background queue. As soon as the query is complete, the handler is executed on the same background queue (but not necessarily the same thread).