A query that returns a snapshot of all matching documents currently saved in the HealthKit store.
SDKs
- iOS 10.0+
- watchOS 3.0+
Framework
- Health
Kit
Declaration
class HKDocumentQuery : HKQuery
Overview
Use an HKDocument
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:
Create the document type by calling the
HKObject
class’sType document
method.Type(for Identifier:) (optionally) Create an
NSPredicate
object to filter the search results.(optionally) Create an array of
NSSort
objects to provide the sort order for the results.Descriptor Instantiate a new query by calling the
init(document
method.Type: predicate: limit: sort Descriptors: include Document Data: results Handler:) 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 tofalse
, the query is still active and will call the results handler with additional results. If thedone
parameter is set totrue
, 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...
}
return
}
allDocuments += results
if done {
// the allDocuments array now contains all the samples returned by the query.
// Handle the documents here...
}
}
Subclassing Document Queries
Like many HealthKit classes, the HKDocument
class should not be subclassed.