所以我一直在遵循这个答案中的说明...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中初始化查询
发布于 2017-07-24 04:32:22
这个特殊的HealthKitQuery是异步的。你应该等到它完成处理。
但是,这种情况在didFinishLaunching中是不可能的。应用程序刚刚结束执行,没有足够的时间处理查询。
我强烈建议重新思考代码操作背后的逻辑。解决此问题的一个好方法是将请求放在其他地方,最好是在完成所需的操作之后。
https://stackoverflow.com/questions/45269527
复制相似问题