有没有办法用健康包读取Apple Watch运动数据?

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

healthkit 中保存了活动卡路里、站立时间和锻炼,但运动数据似乎只存储在 Activity 应用程序中,而没有存储在 healthkit 中。有什么方法可以访问此信息?

不幸的是,应用程序无法访问绿色的锻炼环数据。你应该向 Apple 提交一份雷达,要求它被 HealthKit 公开。

从 iOS 9.3 开始,您可以通过新的 HKActivitySummaryQuery 读取每个 activity 环,这将 return 包含详细信息的 HKActivitySummary 对象每个戒指。 sample code from Apple如下:

// 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)

您感兴趣的作品是 HKActivitySummaryappleExerciseTime 属性。

请注意,此代码不包含您为阅读 HKObjectType.activitySummaryType() 的 activity 摘要所需的授权请求。无法将 HKActivitySummary 写入 HealthKit,因此如果您请求写入权限,应用程序将崩溃。