HKStatisticsQueryDescriptor
A query descriptor that calculates the minimum, maximum, average, or sum over a set of samples from the HealthKit store.
Declaration
struct HKStatisticsQueryDescriptorMentioned in
Overview
Use the HKStatisticsQueryDescriptor to perform calculations over sets of samples currently saved in the HealthKit store.
// Create a predicate for today's samples.
let calendar = Calendar(identifier: .gregorian)
let startDate = calendar.startOfDay(for: Date())
let endDate = calendar.date(byAdding: .day, value: 1, to: startDate)
let today = HKQuery.predicateForSamples(withStart: startDate, end: endDate)
// Create the query descriptor.
let stepType = HKQuantityType(.stepCount)
let stepsToday = HKSamplePredicate.quantitySample(type: stepType, predicate:today)
let sumOfStepsQuery = HKStatisticsQueryDescriptor(predicate: stepsToday, options: .cumulativeSum)
// Run the query.
let stepCount = try await sumOfStepsQuery.result(for: store)?
.sumQuantity()?
.doubleValue(for: HKUnit.count())
// Use the step count here.