init(sampleType:predicate:limit:sortDescriptors:resultsHandler:)
Instantiates and returns a sample query.
Declaration
init(sampleType: HKSampleType, predicate: NSPredicate?, limit: Int, sortDescriptors: [NSSortDescriptor]?, resultsHandler: @escaping @Sendable (HKSampleQuery, [HKSample]?, (any Error)?) -> Void)Parameters
- sampleType:
The type of sample to search for. This object can be an instance of the Hkcategorytype, Hkcorrelationtype, Hkquantitytype, or Hkworkouttype class.
- predicate:
A predicate that limits the results returned by the query. Pass
nilto receive all the samples of the specified type. - limit:
The maximum number of samples returned by the query. If you want to return all matching samples, use Hkobjectquerynolimit.
- sortDescriptors:
An array of sort descriptors that specify the order of the results returned by this query. Pass
nilif you don’t need the results in a specific order. - resultsHandler:
A block that is called when the query finishes executing.
This block takes the following parameters:
- query
A reference to the query that called this block.
- results
An array containing the samples found by the query, or
nilif an error occurs.- error
If an error occurs, this parameter contains an object describing the error. Otherwise, its value is
nil.
Mentioned in
Return Value
A newly initialized sample query object.
Discussion
After instantiating the query, call the HKHealthStore class’s execute(_:) method to run this query. Queries run on an anonymous background queue. As soon as the query is complete, the results handler is executed on the background queue. You typically dispatch these results to the main queue to update the user interface.