ios - 后台模式下的 HKObserverQuery

标签 ios iphone swift apple-watch healthkit

我有一个应用程序需要跟踪来自 Apple Watch 的用户心率读数,所以我执行了在 Apple Guides 上找到的所有必需步骤,这是我正在使用的代码:

static var query: HKObserverQuery?

    func startObservingHeartRate() {

        guard let heartRateSampleType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else {

            fatalError("Unable to create a step count sample type")

        }



        AppDelegate.query = HKObserverQuery(sampleType: heartRateSampleType, predicate: nil, updateHandler: { (query, completionHandler, error) in

                if error != nil {

                    // Perform Proper Error Handling Here...
                    print("An error occured while setting up the Heart Rate observer.")

                }

                //Read the last strored heatt rate in add it to the DB
                //Add last fetched Heart Rate reading to DB and send it to clips
                HealthKitManager().fetchLastStoredHeartRate(completion: { (lastReading, error) in

                    guard let lastReading = lastReading else {

                        //There is no heart readings in HealthKit
                        return

                    }

                    //Check if Last HR value is Abnormal
                    if lastReading.doubleValue > 60 {

                        //TODO: - Schedule notification
                        if UIApplication.shared.applicationState == .background {



                        } else {

                        //TODO: - Show popup to the user

                        }

                    }

                })

                completionHandler()

        })

        healthKitStore.execute(AppDelegate.query!)

        configureHeartRateObserver()

    }

    func configureHeartRateObserver() {

        guard let heartRateSampleType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else {

            fatalError("Unable to create a step count sample type")

        }   

        healthKitStore.enableBackgroundDelivery(for: heartRateSampleType, frequency: HKUpdateFrequency.immediate) { (success, error) in

            if success {

                print("Enabled background delivery of Heart Rate changes")

            } else {

                print("Failed to enable background delivery of weight changes. ")

            }

        }

    }

并且我在 AppDelegate 的 didFinishLaunchingWithOptions 中调用“startObservingHeartRate”,假设一旦从健康工具包商店添加或删除新读数,就应该执行此查询,如果应用程序在后台或杀死处理程序唤醒,一切都很好打开我的应用程序,它会进行更新。

但是每当我将应用程序置于后台然后再次将其置于前台时,即使没有新的读数添加到 HealthKit 存储中,它也会多次执行观察者查询,在这种情况下,我得到的上次心率相同多次无缘无故。

请就如何使用此类查询或我需要对当前实现进行的任何更改提出任何建议。

最佳答案

如果您想更精确地跟踪添加和删除的心率样本,您应该使用 HKAnchoredObjectQuery . HKObserverQuery不保证只有在添加或删除样本时才会调用其更新处理程序。请注意,您必须继续执行 HKObserverQuery除了HKAnchoredObjectQuery因为你也在使用 enableBackgroundDelivery(for:frequency:completion:) .

关于ios - 后台模式下的 HKObserverQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44555628/

相关文章:

ios - 在 Swift 4 中从计算变量创建关键路径

ios - contentOffset 跳过日志中的值

ios - 如何检测 UITextField 外的点击(关闭键盘)

ios - 如何检测 iPhone 是否刚刚连接到互联网?

iphone - ios5 UISearchBar 过滤 TableView 导致空单元格断言错误

ios - 使用前置摄像头进行手势检测

ios - AVMetadataFaceObject 偏航角反转/相反取决于设备型号

post - AFNetworking 2.0 POST 请求无法快速运行

iOS : how to launch app automatically

ios - 在 swiftui 中使用类