HKActivitySummaryQueryDescriptor
A query interface that reads activity summaries using Swift concurrency.
Declaration
struct HKActivitySummaryQueryDescriptorMentioned in
Overview
Use HKActivitySummaryQueryDescriptor to run a query that reads activity summary objects from the HealthKit store. To get a snapshot of activity summaries currently in the store, create a descriptor and call its result(for:) method.
// Get the start and end date components.
let calendar = Calendar(identifier: .gregorian)
var startComponents = calendar.dateComponents([.day, .month, .year], from: Date())
startComponents.hour = 0
startComponents.minute = 0
startComponents.second = 0
var endComponents = startComponents
endComponents.day = 1 + (endComponents.day ?? 0)
// Create a predicate for the query.
let today = HKQuery.predicate(forActivitySummariesBetweenStart: startComponents, end: endComponents)
// Create the descriptor.
let activeSummaryDescriptor = HKActivitySummaryQueryDescriptor(predicate:today)
// Run the query.
let results = try await activeSummaryDescriptor.result(for: store)To set up a long-running query that returns both matching values currently in the HealthKit store, and any updates that arrive while the query is running, call the results(for:) method instead.
// Run a long-running query and monitor for updates.
let updateQueue = activeSummaryDescriptor.results(for: store)
// Wait for the initial results and updates.
updateTask = Task {
for try await results in updateQueue {
// Process results here.
}
}