swift - 在 Series 5 Watch 和 Watch OS6 上使用 `HKAnchoredObjectQuery` 返回心率值时出现问题

标签 swift apple-watch healthkit watchos heartrate

我正在使用 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 应用程序的设置中将锻炼省电模式设置为打开。除非我不小心设置了,否则在安装 Watch OS 6 时它会被设置为开启?关闭后心率查询再次正常返回。

关于swift - 在 Series 5 Watch 和 Watch OS6 上使用 `HKAnchoredObjectQuery` 返回心率值时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58589938/

相关文章:

ios - 在快速将其发送到 Apple Watch 之前缩放高分辨率图像

ios - 用于 Force Touch/Digital Crown 的 WatchKit API?

ios - 在 Apple Watch 中使用代表

ios - 在 iOS 上,如果没有 Apple Watch,如何收集锻炼时消耗的总能量?

swift - iOS 8.0.2 库未加载 libswiftCore.dylib

ios - HKHealthStore deleteObjects 报错 Domain=com.apple.healthkit Code=100 "Transaction failure."

ios - 如何将表情符号转换为表情符号?

ios - 调用 resignFirstResponder 在覆盖 firstResponder 中不起作用

ios - 引用 UICollectionView header 补充 View 的更简洁、更不脆弱的方式

iOS - 本地保存键值对数组