2

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

4 回答 4

3

我在同一个 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 ?? "")
        }
    }
}

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

于 2018-01-17T15:58:36.547 回答
2

我有一个类似的问题,我多年来一直在排除故障。结果由于某种原因,尽管updateHandler在查询中设置了,但即使将新样本添加到 HealthStore 也不会触发它。我认为这是最新操作系统(4.2)的问题。

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

于 2018-01-08T00:58:09.050 回答
1

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

于 2017-12-19T03:53:07.933 回答
-1

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

于 2017-11-22T13:38:11.960 回答