The HKDocumentQuery class is a concrete subclass of the HKQuery class, that provides an interface for retrieving documents from the HealthKit store.


Use an HKDocumentQuery object to search for documents in the HealthKit store. You can provide a predicate to filter the search results, a sort order for the returned samples, or even a limit to the number of samples returned.

Document queries are immutable: The query’s properties are set when the query is first created. They cannot change.

Executing Queries

To create and execute a query, perform the following steps:

  1. Create the document type by calling the HKObjectType class’s documentType(forIdentifier:) method.

  2. (optionally) Create an NSPredicate object to filter the search results.

  3. (optionally) Create an array of NSSortDescriptor objects to provide the sort order for the results.

  4. Instantiate a new query by calling the init(documentType:predicate:limit:sortDescriptors:includeDocumentData:resultsHandler:) method.

  5. In the results handler, handle any errors and process the results.

    Note, the query returns the results in batches and may call the results handler more than once. If the done parameter is set to false, the query is still active and will call the results handler with additional results. If the done parameter is set to true, the query is complete.

guard let cdaType = HKObjectType.documentType(forIdentifier: .CDA) else {
    fatalError("Unable to create a CDA document type.")
var allDocuments = [HKDocumentSample]()
let cdaQuery = HKDocumentQuery(documentType: cdaType,
                               predicate: nil,
                               limit: HKObjectQueryNoLimit,
                               sortDescriptors: nil,
                               includeDocumentData: false) {
                                (query, resultsOrNil, done, errorOrNil) in
                                guard let results = resultsOrNil else {
                                    if let queryError = errorOrNil {
                                        // Handle the query error here...
                                allDocuments += results
                                if done {
                                    // the allDocuments array now contains all the samples returned by the query.
                                    // Handle the documents here...

Subclassing Notes

Like many HealthKit classes, the HKDocumentQuery class should not be subclassed.


Accessing the Document Query’s Properties

var includeDocumentData: Bool

A Boolean value that indicates whether the sample includes the full document’s data.

var limit: Int

The maximum number of documents the receiver will return upon completion.

var sortDescriptors: [NSSortDescriptor]?

An array of sort descriptors that specify the order of the results returned by this query.


Inherits From

Conforms To