如何在不提示非 HK 用户获取权限的情况下使用后台交付的 Healthkit 观察者查询?

How do I use Healthkit observer queries with background delivery without prompting non-HK users for permissions?

此应用的用户可以选择是否要使用 Healthkit 功能(应用运行不需要这些功能)。我想设置一个观察者查询来在后台向服务器发送数据。

根据此处 link 的 Apple 文档:https://developer.apple.com/documentation/healthkit/hkobserverquery/executing_observer_queries

If you plan on supporting background delivery, set up all your observer queries in your app delegate’s application:didFinishLaunchingWithOptions: method. By setting up the queries in application:didFinishLaunchingWithOptions:, you ensure that the queries are instantiated and ready to use before HealthKit delivers the updates.

据我了解,在 application:didFinishLaunchingWithOptions: 方法中设置您的观察者查询意味着我必须在首次启动时提示用户授予权限。是否可以从其他地方设置后台传送?例如,我是否可以在提示用户权限的同时执行此操作?

谢谢!

一个可能的流程是:

  • didFinishLaunching 中,检查 UserDefaults 是否有布尔值表明用户已批准 HealthKit 集成。如果是 true 则调用一个函数来设置您的观察者查询。

  • 在您的应用执行过程中,当用户表示他们想要提供对 HealthKit 数据的访问权限时,提示您获得许可,然后在获得许可后在 UserDefaults 中设置布尔值。

  • 此时您还可以调用您的函数来设置您的观察者查询,以便您开始接收数据。