简体   繁体   中英

Is there a way to read the Apple Watch exercise data with health kit?

Active calories, stand hours and workouts are saved in healthkit, but it seems that exercise data is stored only in Activity app but not in healthkit. Are there any way to access this information?

As of iOS 9.3, you can read each of the activity rings via the new HKActivitySummaryQuery which will return an HKActivitySummary object containing details of each ring. The sample code from Apple is as follows:

// 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 startDateComponents = calendar.components(units, fromDate: startDate)
startDateComponents.calendar = calendar

let endDateComponents = calendar.components(units, fromDate:endDate)
endDateComponents.calendar = calendar

let startDateComponents = calendar.components(units, fromDate: startDate)


// 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...
    if let summary = summaries?.first {
        NSLog("Exercise: \(summary.appleExerciseTime)")
    }
}

// Run the query
store.executeQuery(query)

The piece you'll be interested in is the appleExerciseTime property of the HKActivitySummary .

Please note that this code doesn't include the authorisation request you'll need to make to be able to read the activity summary which is of HKObjectType.activitySummaryType() . It is not possible to write HKActivitySummary to HealthKit so the app will crash if you request write permissions.

The green Exercise ring data is unfortunately not accessible to apps. You should file a radar with Apple to ask for it to be exposed by HealthKit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM