Contents

HKStatisticsCollectionQueryDescriptor

A query descriptor that gathers a collection of statistics calculated over a series of fixed-length time intervals.

Declaration

struct HKStatisticsCollectionQueryDescriptor

Mentioned in

Overview

Use HKStatisticsCollectionQueryDescriptor to run a query that calculates statistics grouped into time intervals. To get a snapshot of the current data in the store, create a descriptor and call its result(for:) method.

// Create a predicate for this week's samples.
let calendar = Calendar(identifier: .gregorian)
let today = calendar.startOfDay(for: Date())

guard let endDate = calendar.date(byAdding: .day, value: 1, to: today) else {
    fatalError("*** Unable to calculate the end time ***")
}

guard let startDate = calendar.date(byAdding: .day, value: -7, to: endDate) else {
    fatalError("*** Unable to calculate the start time ***")
}

let thisWeek = HKQuery.predicateForSamples(withStart: startDate, end: endDate)

// Create the query descriptor.
let stepType = HKQuantityType(.stepCount)
let stepsThisWeek = HKSamplePredicate.quantitySample(type: stepType, predicate:thisWeek)
let everyDay = DateComponents(day:1)

let sumOfStepsQuery = HKStatisticsCollectionQueryDescriptor(
    predicate: stepsThisWeek,
    options: .cumulativeSum,
    anchorDate: endDate,
    intervalComponents: everyDay)

let stepCounts = try await sumOfStepsQuery.result(for: store)

// Use the statistics collection here.

To set up a long-running query that updates the calculations based on any new data that arrives while it’s running, call the results(for:) method instead. The first result contains calculations based on samples currently in the HealthKit store, and additional results represent updates as they occur.

// Run a long-running query that updates its statistics as new data comes in.
let updateQueue = sumOfStepsQuery.results(for: store)

// Wait for the initial results and updates.
updateTask = Task {
    for try await results in updateQueue {
        // Use the statistics collection here.
    }
}

Topics

Creating Query Descriptors

Running Queries

Accessing Query Properties

Structures

Default Implementations

See Also

Statistics