A query that performs statistical calculations over a set of matching quantity samples, and returns the results.


class HKStatisticsQuery : HKQuery


Statistics queries can calculate the minimum, maximum, and average value for discrete quantities. They can also calculate the sum for cumulative quantities. For more information about the available quantity types and to learn whether they are discrete or cumulative values, see Data Types.

You can use statistics queries with quantity samples only. If you want to calculate statistics over workouts or correlation samples, you must perform the appropriate query and process the data yourself.

Statistics queries are immutable. Their properties are set when they are first created, and they cannot change.

Executing Statistics Queries

You create a sample query by calling the init(quantityType:quantitySamplePredicate:options:completionHandler:) initializer. After the query is instantiated, you run it by calling the HealthKit store’s execute(_:) method. This method runs the query on a anonymous background queue. When the query is complete, it executes the results handler on the same background queue (but not necessarily on the same thread). Typically, you dispatch these results back to the main queue to update your user interface.

The sample code in Listing 1 builds a statistics query and processes the results. This function is taken from the AAPLEnergyViewController.m file in Fit: Store and Retrieve HealthKit Data.

Listing 1

Fetching total joules

func fetchTotalJoulesConsumedWithCompletionHandler(
    completionHandler:(Double?, NSError?)->()) {
    let calendar = NSCalendar.currentCalendar()
    let now = NSDate()
    let components = calendar.components(.YearCalendarUnit |
        .MonthCalendarUnit | .DayCalendarUnit, fromDate: now)
    let startDate = calendar.dateFromComponents(components)
    let endDate = calendar.dateByAddingUnit(.DayCalendarUnit,
                                            value: 1, toDate: startDate, options: NSCalendarOptions(nil))
    let sampleType = HKQuantityType.quantityTypeForIdentifier(
    let predicate = HKQuery.predicateForSamplesWithStartDate(startDate,
                                                             endDate: endDate, options: .StrictStartDate)
    let query = HKStatisticsQuery(quantityType: sampleType,
                                  quantitySamplePredicate: predicate,
                                  options: .CumulativeSum) { query, result, error in
                                    if result != nil {
                                        completionHandler(nil, error)
                                    var totalCalories = 0.0
                                    if let quantity = result.sumQuantity() {
                                        let unit = HKUnit.jouleUnit()
                                        totalCalories = quantity.doubleValueForUnit(unit)
                                    completionHandler(totalCalories, error)

The sample code in Listing 1 defines a method that calculates the total energy consumed today. This method starts by calculating the start and end dates for the desired time interval. This method produces a 24-hour period, starting at the previous midnight. Next, it defines a sample type for dietary energy consumed and a predicate that filters out any samples that don’t fall within the desired time interval.

With the sample type and predicate created, it builds the statistics query. This query sums up the total amount of dietary energy consumed during the specified time frame. As soon as the calculations are done, the query calls its results handler.

The results handler checks to see whether an error occurred. If there is an error, it passes the error back to the completion handler. Otherwise, it obtains the sum quantity from the results and requests its value in joules. Then it passes this value back to the completion handler.

After the result handler’s block is defined, the query is complete. The sample code simply executes this query using the HealthKit store.


Creating Statistics Queries

init(quantityType: HKQuantityType, quantitySamplePredicate: NSPredicate?, options: HKStatisticsOptions, completionHandler: (HKStatisticsQuery, HKStatistics?, Error?) -> Void)

Initializes a statistics query instance that performs the specified calculations over the matching samples in the HeathKit store.


Inherits From

Conforms To

See Also

Calculating Statistics

class HKStatisticsCollectionQuery

A query that performs multiple statistics queries over a series of fixed-length time intervals, and returns the results.

class HKStatistics

An object that represents the result of calculating the minimum, maximum, average, or sum over a set of samples from the HealthKit store.

class HKStatisticsCollection

An object that manages a collection of statistics; each statistics object represents the data calculated over a separate time interval.

struct HKStatisticsOptions

Options for specifying the statistic to calculate.