Contents

init(queryDescriptors:limit:resultsHandler:)

Creates a query for samples that match any of the descriptors you provided.

Declaration

init(queryDescriptors: [HKQueryDescriptor], limit: Int, resultsHandler: @escaping  @Sendable (HKSampleQuery, [HKSample]?, (any Error)?) -> Void)

Parameters

  • queryDescriptors:

    An array of descriptors that specify the types of samples that the query returns.

  • limit:

    The maximum number of samples that the query return. If you want to return all matching samples, use Hkobjectquerynolimit.

  • resultsHandler:

    A block that the HealthKit store calls after it finishes executing the query.

    This block takes the following parameters:

    query

    A reference to the query that called this block.

    results

    An array containing the samples the query found, or nil if an error occurs.

    error

    If an error occurs, an object describing the error; otherwise, it’s nil.

Discussion

Use this initializer to create a sample query for data that matches any of the HKQueryDescriptor objects. Each descriptor can specify a different data type.

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 system executes the results handler on the background queue, returning samples that match any of the descriptors. You typically dispatch these results to the main queue to update the user interface.

For example, the following code returns all the step count and push count samples:

// Create the data types.
let stepCountType = HKQuantityType(.stepCount)
let pushCountType = HKQuantityType(.pushCount)

// Specify the desired sample types.
let stepDescriptor = HKQueryDescriptor(sampleType: stepCountType, predicate: nil)
let pushDescriptor = HKQueryDescriptor(sampleType: pushCountType, predicate: nil)

// Create the query.
let query = HKSampleQuery(queryDescriptors: [stepDescriptor, pushDescriptor],
                          limit: HKObjectQueryNoLimit) { (query, samples, error) in
    
    if let error = error {
        // Handle errors here.
    }
    
    
    DispatchQueue.main.async {
        // Process the samples here.
    }
}

// Run the query.
store.execute(query)

See Also

Creating Sample Queries