1

所以我一直在遵循这个答案中的说明...... 应用程序未运行时的 Healthkit 后台交付

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

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 中初始化

4

1 回答 1

0

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

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

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

于 2017-07-23T20:32:21.840 回答