【发布时间】:2016-11-29 09:03:35
【问题描述】:
是否可以从 HealthKit 读取 Apple Watch 移动目标?
我可以使用数量标识符 HKQuantityTypeIdentifier.activeEnergyBurned 检索移动值。我找不到移动目标的类似标识符。
【问题讨论】:
标签: ios apple-watch watchos
是否可以从 HealthKit 读取 Apple Watch 移动目标?
我可以使用数量标识符 HKQuantityTypeIdentifier.activeEnergyBurned 检索移动值。我找不到移动目标的类似标识符。
【问题讨论】:
标签: ios apple-watch watchos
//Declared globally
var healthStore: HKHealthStore?
func prepareHealthKit() {
guard HKHealthStore.isHealthDataAvailable() else {
return
}
var readTypes = Set<HKObjectType>()
readTypes.insert(HKObjectType.activitySummaryType())
healthStore = HKHealthStore()
healthStore!.requestAuthorization(toShare: nil, read: readTypes) { (isSuccess, error) in
/*
Assuming you know the following steps:
1. Start workout session: i.e. "HKWorkoutSession"
2. Wait for delegate: i.e "workoutSession(_:didChangeTo:from:date:)"
3. Start Query for Activity Summary in the delegate:
i.e our "startQueryForActivitySummary()"
*/
}
}
func startQueryForActivitySummary() {
func createPredicate() -> NSPredicate? {
let calendar = Calendar.autoupdatingCurrent
var dateComponents = calendar.dateComponents([.year, .month, .day],
from: Date())
dateComponents.calendar = calendar
let predicate = HKQuery.predicateForActivitySummary(with: dateComponents)
return predicate
}
let queryPredicate = createPredicate()
let query = HKActivitySummaryQuery(predicate: queryPredicate) { (query, summaries, error) -> Void in
if let summaries = summaries {
for summary in summaries {
let activeEnergyBurned = summary.activeEnergyBurned.doubleValue(for: HKUnit.kilocalorie())
let activeEnergyBurnedGoal = summary.activeEnergyBurnedGoal.doubleValue(for: HKUnit.kilocalorie())
let activeEnergyBurnGoalPercent = round(activeEnergyBurned/activeEnergyBurnedGoal)
print(activeEnergyBurnGoalPercent)
}
}
}
healthStore?.execute(query)
}
参考资料:
【讨论】:
我得到了答案。移动目标可从HKActivitySummary 访问。
您应该请求读取 HKActivitySummaryType 的权限:
let activitySummaryType = HKActivitySummaryType.activitySummaryType()
let readDataTypes: Set<HKObjectType> = [activitySummaryType]
healthStore.requestAuthorization(toShare: nil, read: readDataTypes, completion: myCompletionHandler)
然后使用HKActivitySummaryQuery阅读摘要信息
let query = HKActivitySummaryQuery(predicate: myPredicate) { (query, summaries, error) -> Void in
if error != nil {
fatalError("*** Did not return a valid error object. ***")
}
if let activitySummaries = summaries {
for summary in activitySummaries {
print(summary.activeEnergyBurnedGoal)
//do something with the summary here...
}
}
}
healthStore.execute(query)
可从 HKActivitySummary 访问的其他活动摘要数据可通过here 获取。
【讨论】: