【问题标题】:HKObserverQuery only runs when the application is reopenedHKObserverQuery 仅在应用程序重新打开时运行
【发布时间】:2017-07-23 20:17:42
【问题描述】:

所以我一直按照这个答案中的说明进行操作...... Healthkit background delivery when app is not running

代码运行良好并且在应用程序打开时工作,并说后台交付成功,但是当我通过四处走动并将设备上的时钟更改为一个小时前来测试应用程序时,我没有收到任何日志让我知道它已经运行了。但是,如果我再次打开应用程序,观察者查询就会运行。

private func checkAuthorization(){
    let healthDataToRead = Set(arrayLiteral: self.distanceQuantityType!)


    healthKitStore.requestAuthorization(toShare: nil, read: healthDataToRead) { (success, error) in
        if error != nil {
            print(error?.localizedDescription)
            print("There was an error requesting Authorization to use Health App")
        }
        if success {
            print("success")

        }
    }

}
public func enableBackgroundDelivery() {

    self.checkAuthorization()
    self.healthKitStore.enableBackgroundDelivery(for: self.distanceQuantityType!, frequency: .hourly) { (success, error) in
        if success{
            print("Background delivery of steps. Success = \(success)")

        }

        if let error = error {
            print("Background delivery of steps failed = \(error.localizedDescription)")
        }
    }



}

func observeDistance(_ handler:@escaping (_ distance: Double) -> Void) {

    let updateHandler: (HKObserverQuery?, HKObserverQueryCompletionHandler?, Error?) -> Void = { query, completion, error in
        if !(error != nil) {
            print("got an update")
            completion!()
        } else {
            print("observer query returned error: \(error)")
        }
    }

    let query = HKObserverQuery(sampleType: self.distanceQuantityType!, predicate: nil, updateHandler: updateHandler)
    self.healthKitStore.execute(query)
}

查询在appDelegate方法didFinishLaunching中初始化

【问题讨论】:

    标签: ios swift healthkit background-fetch hkobserverquery


    【解决方案1】:

    这个特定的 HealthKitQuery 是异步的。您应该等到它完成处理。

    但是,这种情况在didFinishLaunching 中是不可能的。应用程序刚刚结束执行,没有足够的时间来处理查询。

    我会认真建议重新考虑代码操作背后的逻辑。解决此问题的一个好方法是将请求放在其他地方,最好是在完成所需的操作之后。

    【讨论】:

    • 根据文档,观察者查询应始终在 didFinishLaunching 中初始化。我觉得有某种错误阻止了代码在后台运行,因为当再次打开应用程序时它可以完美运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 2020-12-15
    • 2012-07-03
    • 1970-01-01
    • 2014-01-30
    • 2011-07-02
    相关资源
    最近更新 更多