在 WWDC 2017 上,Apple 宣布添加vo2Max作为新的数量样本。为了返回 vo2Max 样本,必须有哪些变量?根据 Vo2Max 下的 Health App,“Apple Watch 会在您进行严格的户外步行或在 Workout 应用程序中跑步至少 20 分钟并持续测量心率时记录您预测的 vo2Max。” 听起来好像它对 3rd 方应用程序不可用,但是WWDC 2017 上 3:20 的这个剪辑听起来好像它应该可用?
.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 的文档非常少。