Source queries let you search for the sources (apps and devices) that have saved data to the HealthKit store. These queries return a set containing all the sources for any samples that match the query.


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