在WWDC 2017上,Apple宣布增加vo2Max作为新的数量样本。为了返回vo2Max样本,必须有哪些变量?根据Vo2Max下的健康应用程序“Apple Watch在您进行严格的户外散步时记录您预测的vo2Max,或在锻炼应用中运行至少20分钟并持续进行心率测量。”听起来好像它不适用于第三方应用程序,但是在2017年WWDC 2017上的this剪辑会让它听起来好像应该可用吗?
在.running户外锻炼期间,以下代码即使在20分钟后也会返回并清空阵列:
func startVO2MaxQuery(from startDate: Date, updateHandler: @escaping ([HKQuantitySample]) -> Void) {
let typeIdentifier = HKQuantityTypeIdentifier.vo2Max
startQuery(ofType: typeIdentifier, from: startDate) { _, samples, _, _, error in
guard let quantitySamples = samples as? [HKQuantitySample] else {
print("Heart rate query failed with error: \(String(describing: error))")
return
}
print("VO2Max samples = \(quantitySamples)")
updateHandler(quantitySamples)
}
}
private func startQuery(ofType type: HKQuantityTypeIdentifier, from startDate: Date, handler: @escaping
(HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void) {
let datePredicate = HKQuery.predicateForSamples(withStart: startDate, end: nil, options: .strictStartDate)
let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
let queryPredicate = NSCompoundPredicate(andPredicateWithSubpredicates:[datePredicate, devicePredicate])
let quantityType = HKObjectType.quantityType(forIdentifier: type)!
let query = HKAnchoredObjectQuery(type: quantityType, predicate: queryPredicate, anchor: nil,
limit: HKObjectQueryNoLimit, resultsHandler: handler)
query.updateHandler = handler
healthStore.execute(query)
activeDataQueries.append(query)
}
权限
private func requestAccessToHealthKit() {
let healthStore = HKHealthStore()
let allTypes = Set([HKObjectType.workoutType(),
HKSeriesType.workoutRoute(),
HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!,
HKObjectType.quantityType(forIdentifier: .heartRate)!,
HKObjectType.quantityType(forIdentifier: .vo2Max)!,
HKObjectType.quantityType(forIdentifier: .stepCount)!,
HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!])
healthStore.requestAuthorization(toShare: allTypes, read: allTypes) { (success, error) in
if !success {
print("failed HealthKit Authorization from iPhone \(String(describing: error?.localizedDescription))")
}
print("Successful HealthKit Authorization directly from the watch")
}
}
还有什么我需要做的吗? Apple的文档非常稀少。