A query that returns a list of sources (apps and devices) that have saved matching queries to the HealthKit store.


class HKSourceQuery : HKQuery


Source queries are immutable: Their properties are set when they are first created, and they cannot change.

Executing Source Queries

You create a source query by calling the init(sampleType:samplePredicate:completionHandler:) initializer. After the query is instantiated, you run it by calling the HealthKit store’s execute(_:) method. This runs the query on a anonymous background queue. When the query is complete, it executes the results handler on the same background queue (but not necessarily the same thread).

The sample code in Listing 1 builds a source query and processes the results.

Listing 1

Building a source query

let sampleType =
let query = HKSourceQuery(sampleType: sampleType, samplePredicate: nil) {
    query, sources, error in
    if error != nil {
        // Perform Proper Error Handling Here...
        println("*** An error occured while gathering the sources for step date. \(error.localizedDescription) ***")
    for object: AnyObject in sources {
        if let source = object as? HKSource {

Listing 1 creates a query to find all the sources for step data. It starts by creating a sample type for the step counts. Then it creates the query itself. The query wants to gather all the sources for any step data samples in the HealthKit store, so it passes in a nil predicate. In the callback handler, the sample code checks to see whether an error occurred. If there isn’t an error, the code iterates over the set of sources, processing each source.

After the sample defines the callback handler’s block, the query is complete. The sample code simply executes this query using the HealthKit store.


Inherits From

Conforms To

See Also

Sources and Devices

class HKSourceRevision

An object indicating the source of a HealthKit sample.

class HKSource

An object indicating the app or device that created a HealthKit sample

class HKDevice

A device that generates data for HealthKit.