使用来自 SpeedySloth 的 Apple 示例代码,我在模拟器上获取了心率样本,但在运行 WatchOS 4.1 的 Series 0 Apple Watch 上未获取任何样本。这是一个错误吗?还有谁有相同的问题吗?
代码:
func startHeartRateQuery(from startDate: Date, updateHandler: @escaping ([HKQuantitySample]) -> Void) {
let typeIdentifier = HKQuantityTypeIdentifier.heartRate
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("heartRate samples = \(quantitySamples)")
updateHandler(quantitySamples)
}
}
//Generic helper function
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)
}
最佳答案
我在相同的 Apple 示例代码上遇到了完全相同的问题。几个月前在 WatchOS 4.1 上尝试过,我可以放心地假设它从 4.2 开始就坏了。
但是,我只需向健康商店请求必要的香港授权即可使其发挥作用。只需像这样重写初始化程序或 HealthStoreManager.swift 即可:
// HealthStoreManager.swift
override init() {
super.init()
let allTypes = Set([HKObjectType.workoutType(),
HKSeriesType.workoutRoute(),
HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!,
HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!])
healthStore.requestAuthorization(toShare: allTypes, read: allTypes) { (success, error) in
if !success {
print(error?.localizedDescription ?? "")
}
}
}
从头开始重新安装应用程序,它现在应该可以正常工作。
关于ios - WatchOS 4 未接收心率样本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47099944/