我正在使用HKAnchoredObjectQuery
查询心率,因为我不想为此应用程序使用WorkoutBuilder API。该查询始终以正常采样率(每秒等)在锻炼过程中返回心率,但我注意到在Series 5 Watch OS 6.1上进行测试时,我只会看到非常零星的采样,例如一小时内获取5个心率。 HKAnchoredObjectQuery
的文档中没有任何内容已弃用。知道为什么这种心率采集方法不再有效吗?
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
}
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)
}
很奇怪,但事实证明我在Watch App的设置中将“锻炼节电模式”设置为打开。除非意外设置,否则在安装Watch OS 6时将其设置为打开?将其关闭后,心率查询将再次正常返回。