在后台定期检查 healthkit 数据 swift

Checking healthkit data periodically in background swift

我正在为启用了 HealthKit 的 iOS 应用编程一个不活动警报。当用户在过去 60 分钟内走的步数少于 100 步时,它会根据 Health 中的数据发送通知。当应用程序打开时,这非常有效,但我在后台运行时遇到了一些问题。我已尝试使用本教程 (https://www.raywenderlich.com/92428/background-modes-ios-swift-tutorial) 中描述的后台位置检查程序获取步数数据,但由于某些原因,当本教程的程序 运行 在真实 iPhone。

所以,我的问题是:我的应用程序如何才能在后台每分钟可靠地检查健康数据,即使应用程序已关闭数天?

当设备被锁定时,HealthKit 数据库会被加密。这意味着当设备要求您输入 passcode/fingerprint(大多数设备已启用)时,您根本无法从中读取任何数据。所以不幸的是,即使你每分钟都能在后台 运行 得到一些东西,你也无法读取数据(你的查询只会 return 一个错误而不是任何结果)。

但是,仍然可以从计步器访问步数数据(此数据未加密)。我建议您考虑使用它代替 HealthKit 进行任何后台处理。

现在听起来您真的只需要检查用户是否在过去一小时内完成了步数。如果您只经常而不是每分钟检查一次,效率会高得多。如果您的应用程序可以访问具有推送通知设置的服务器,您可以安排静默推送通知以在后台唤醒您的应用程序,并每小时从计步器进行一次步数检查。

您可以使用 HKObserverQuery:一个长查询 运行 监控 HealthKit 存储并在匹配样本保存到或从中删除时更新您的应用程序HealthKit 商店。

1.First 设置你的观察者查询

let sampleType =
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)

let query = HKObserverQuery(sampleType: sampleType, predicate: nil) {
query, completionHandler, error in

if error != nil {

    // Perform Proper Error Handling Here...
    println("*** An error occured while setting up the stepCount observer. \(error.localizedDescription) ***")
    abort()
}

// Take whatever steps are necessary to update your app's data and UI
// This may involve executing other queries
self.updateDailyStepCount()

// If you have subscribed for background updates you must call the completion handler here.
// completionHandler()
}
healthStore.executeQuery(query)`

2.Then 注册接收后台交付

通过调用 HealthKit 商店的 enableBackgroundDelivery(for:frequency:withCompletion:) 方法注册以在后台接收更新。您可以根据需要设置适当的更新频率。

只要指定类型的新样本保存到商店,HealthKit 就会唤醒您的应用程序。如果您计划支持后台交付,请在您的应用委托的 application(_:didFinishLaunchingWithOptions:) 方法中设置所有观察者查询。通过在 application(_:didFinishLaunchingWithOptions:) 中设置查询,您可以确保在 HealthKit 交付更新之前实例化并准备好使用查询。

更多信息,请查看来源:https://developer.apple.com/documentation/healthkit/hkobserverquery