Class

HKActivitySummaryQuery

A query for read activity summary objects from the HealthKit store.

Overview

Activity summary query objects are mostly immutable. You can assign the query’s updateHandler property after instantiating the object. All other properties must be set when you instantiate the object, and they cannot change.

Executing Activity Summary Queries

The sample code, shown below, builds and executes a query that returns the activity summaries for the previous week.

// Create the date components for the predicate
guard let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) else {
    fatalError("*** This should never fail. ***")
}
 
let endDate = NSDate()
 
guard let startDate = calendar.dateByAddingUnit(.Day, value: -7, toDate: endDate, options: []) else {
    fatalError("*** unable to calculate the start date ***")
}
 
let units: NSCalendarUnit = [.Day, .Month, .Year, .Era]
 
let startDateComponents = calendar.components(units, fromDate: startDate)
startDateComponents.calendar = calendar
 
let endDateComponents = calendar.components(units, fromDate: endDate)
endDateComponents.calendar = calendar
 
 
// Create the predicate for the query
let summariesWithinRange = HKQuery.predicateForActivitySummariesBetweenStartDateComponents(startDateComponents, endDateComponents: endDateComponents)
 
// Build the query
let query = HKActivitySummaryQuery(predicate: summariesWithinRange) { (query, summaries, error) -> Void in
    guard let activitySummaries = summaries else {
        guard let queryError = error else {
            fatalError("*** Did not return a valid error object. ***")
        }
        
        // Handle the error here...
        
        return
    }
    
    // Do something with the summaries here...
}
 
// Run the query
store.executeQuery(query)

This code performs the following steps:

  1. Creates the date component objects representing the start and end days, as perceived by the user.

  2. Creates a predicate object using the date components.

  3. Creates the query object using the predicate.

  4. Executes the query.

Topics

Initializing Activity Summary Queries

Getting Property Data

var updateHandler: ((HKActivitySummaryQuery, [HKActivitySummary]?, Error?) -> Void)?

The handler for monitoring updates to activity summaries saved in the HealthKit store.

Relationships

Inherits From

Conforms To

See Also

Activity Rings

class HKActivitySummary

An object that contains the move, exercise, and stand data for a given day.

class HKActivityRingView

A view that uses the Move, Exercise, and Stand activity rings to display data from a HealthKit activity summary object.