HKDocumentQuery
A query that returns a snapshot of all matching documents currently saved in the HealthKit store.
Declaration
class HKDocumentQueryMentioned in
Overview
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:
Create the document type by calling the HKObjectType class’s documentType(forIdentifier:) method.
(optionally) Create an NSPredicate object to filter the search results.
(optionally) Create an array of NSSortDescriptor objects to provide the sort order for the results.
Instantiate a new query by calling the init(documentType:predicate:limit:sortDescriptors:includeDocumentData:resultsHandler:) method.
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...
}
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 HKDocumentQuery class should not be subclassed.
Topics
Creating Document Queries
init(documentType:predicate:limit:sortDescriptors:includeDocumentData:resultsHandler:)HKObjectQueryNoLimit