HKObserverQuery、后台更新和隐私政策

HKObserverQuery, background updates and privacy policy

我正在尝试使用 HealthKit API 对心率监测器进行编程。

我有一台 Polar H7,它正在将数据写入健康存储。我使用 HKObserverQuery(没有丢失对 completionHandler() 的调用)、HKSampleQuery 并为我正在查询的类型启用调用 HKHealthStore.enableBackgroundDeliveryForType 的后台更新来实现我的目标。

private func queryForHeartRate() {

    guard let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else {
        executeCompletionHandler(value: nil, error: nil)
        return
    }

    let observerQuery = HKObserverQuery(sampleType: sampleType, predicate: nil) { [unowned self] query, completionHandler, error in

        guard error == nil else {
            self.executeCompletionHandler(value: nil, error: error)
            return
        }

        self.queryHeartRateSample(sampleType)
        completionHandler()
    }

    healthStore.executeQuery(observerQuery)
}

private func queryHeartRateSample(sampleType: HKSampleType) {

    let timeSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
    let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: nil, limit: 1, sortDescriptors: [timeSortDescriptor], resultsHandler: { [unowned self] (sampleQuery, results, error) in

        guard error == nil else {
            self.executeCompletionHandler(value: nil, error: error)
            return
        }

        guard let samples = results as? [HKQuantitySample] where !samples.isEmpty else {
            self.executeCompletionHandler(value: nil, error: error)
            return
        }

        guard let lastSample = samples.last else {
            self.executeCompletionHandler(value: nil, error: error)
            return
        }

        let heartBeat = lastSample.quantity.doubleValueForUnit(self.heartBeatsPerMinuteUnit)
        self.executeCompletionHandler(value: heartBeat, error: nil)
    })

    healthStore.executeQuery(sampleQuery)
}

但是当应用程序进入后台或我锁定 phone(即时密码)时,应用程序停止接收更新。

正在阅读 docs 我明白了:

The HealthKit data is only kept locally on the user’s device. For security, the HealthKit store is encrypted when the device is locked. The HealthKit store can only be accessed by an authorized app. As a result, you may not be able to read data from the store when your app is launched in the background; however, apps can still write data to the store, even when the phone is locked. HealthKit temporarily caches the data and saves it to the encrypted store as soon as the phone is unlocked

但是,当我使用 Runstatstic 时,当我更改心脏区域时,我会收到声音建议; Nike+运行 以相同方式追踪所有心率。该隐私政策怎么可能?

我有点迷茫,文档对接收 background/locked 更新所需的内容有点混乱(如果可能的话)。我在 SO 中阅读了所有相关答案,但没有一个是决定性的,有更多信息的那个 this 谈到了后台提取,这是文档中没有提到的事情。

是否有关于如何实现此目的的任何资源或教程?甚至可能吗?有 Runtastic 或类似应用程序解决这个问题吗?

非常感谢。

当设备处于锁定状态时,您的应用无法接收 HealthKit 数据,因为此时数据已加密并且无法访问。其他在设备锁定时响应心率变化的应用很可能是直接从 BT 心率监测器读取数据,而不是 HealthKit。