【发布时间】: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