WatchOS 4没有收到心率样本?

时间:2017-11-03 16:03:56

标签: ios swift apple-watch health-kit watch-os-4

使用来自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)
    }

4 个答案:

答案 0 :(得分:2)

我有一个类似的问题,我一直在排除故障。事实证明,虽然在查询中设置了updateHandler,但即使将新样本添加到HealthStore,也不会触发它。我认为这是最新操作系统(4.2)的问题。

作为替代方案,我使用刷新的查询锚点每5秒轮询一次HealthStore。它现在按预期工作。我有一个状态变量,检查是否继续轮询。

答案 1 :(得分:2)

我在同一个Apple示例代码上遇到了同样的问题。几个月前,我在WatchOS 4.1上尝试过它,我可以放心地认为它自4.2起就已经破了。

然而,我只需要向健康商店申请必要的香港授权即可使其成功。只需覆盖初始化程序或HealthStoreManager.swift,如下所示:

(t1,t2)->t1.sameTemp(t2)

从头开始重新安装应用程序,它现在应该可以正常运行。

答案 2 :(得分:1)

我在使用SpeedySloth应用程序收集数据时遇到了一些问题。花了4天时间阅读关于这个主题的每篇SO帖子并尝试我能想到的一切。我最终删除了我的计算机上的所有旧Xcode版本(我现在只安装了9.2)并且我还删除了~/Library/Logs/CoreSimulator/中的所有模拟器文件并且它最终正常工作。怪异。

答案 3 :(得分:-1)

我最终将手表从0系列升级到3系列,我在WatchOS 4.1上获得心率不再有任何问题。问题可能与硬件有关。发布更新以显示上面的代码有助于提取心率数据。