每当有新数据可用时,我都会尝试让 HealthKit 启动我的应用程序。因此,我尝试按照我在 GitHub 上找到的这个示例将 HKObserverQuery 与后台交付一起使用。
我为我的项目启用了后台模式功能,并确保 Info.plist 中的必需背景模式中只有一项
我正在使用 Xcode 和 IOS 10。我确实意识到某些数据类型有时间限制,所以我通过在模拟器上添加爬升到健康应用程序的航班并查看是否调用了打印方法来测试这一点。但什么都没有发生。我还尝试在 AppDelegate 的 application() 方法中设置断点,但它仅在应用程序第一次启动时执行。在我将条目放入健康应用程序后,它不会被调用。
我在这里做错了什么?或者有什么方法可以查看 Healthkit 是否正在尝试启动我的应用程序?
这是我的 AppDelegate 和其他相关文件
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let manager = HealthKitManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
manager.hkAccessor.setUpObserverQuery(){ samples in
for sample in samples!{
print("\(sample.value) \(sample.identifier)")
}
}
return true
}
HealthkitAccessor:
func setUpObserverQuery(completion:@escaping ([QuantitySample]?) -> ()) {
for type in getDataTypesToRead() {
guard let sampleType = type as? HKSampleType else { print("\(type) is not an HKSampleType"); continue }
let query = HKObserverQuery(sampleType: sampleType, predicate: nil) {
[weak self] query, completionHandler, error in
if error != nil {
print("*** An error occured. \(error!.localizedDescription) ***")
return
}
guard let strongSelf = self else { return }
strongSelf.queryForDataType(type:type) { samples in
completion(samples)
}
completionHandler()
}
executeQuery(query: query)
healthStore.enableBackgroundDelivery(for: type, frequency: .immediate) { (success: Bool, error: Error?) in
if success{
print("\(type) registered for background delivery")
}
else {
print("\(type) registered for background delivery")
}
}
}
}