A query that performs statistical calculations over a set of matching quantity samples, and returns the results.
- iOS 8.0+
- Mac Catalyst 13.0+Beta
- watchOS 2.0+
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(quantity 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 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.