Background Observer Query in App Delegate

Apple's Documentation Class Reference for HKHealthDataStore states that observer queries should be setup within the AppDelegate.

"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."

When a user first opens my app, I need to take them through an Onboarding flow, which involves requesting HealthKit Authorization Permissions, before setting up Observer Queries and querying some initial data. My app is entirely based around Observer Queries, so I need to be able to register for background updates during the first launch of my app.


I'm unsure how I can do this from the AppDelegate? I can't just request HealthKit Authorization immediately the first time a user downloads and opens my app, before they see anything else? Or request Authorization and then tell the user to quit my app, and re-open it so that I can setup observer queries in the App Delegate the second time.

Am I misunderstanding the documentation? Or approaching this wrong?

Any help or suggestions would be greatly appreciated.

Thank you

I didn't find any clear guidance on this issue either. We addressed this by calling twice, once in application:didFinishLaunchingWithOptions: and also in viewDidAppear. So far I have not found problems with this approach, but I can't say whether it is the best way.


Good luck!

Adrian

We are doing the same as @aharriscrowne. Essentially, the app suppresses requesting access to HealthKit and setting up the observer queries until after users have completed the onboarding flow. The observer queries and background delivery enablement actually only get set up when we get a success back from the -requestAuthorizationToShareTypes:readTypes: call (meaning they tapped "Allow").


Then, once the onboarding flow is completed, the same "request access" and "setup background delivery" is called on each app launch from -application:didFinishLaunchingWithOptions: Requesting access multiple times doesn't cause any problems. The Health Access screen will not be presented unles the set of HKObjectType changes. I find this handy because simply changing the set of types the app reads or writes triggers the Health Access screen on the next launch.


Here's a gist showing the general setup: https://gist.github.com/phatblat/654ab2b3a135edf905f4a854fdb2d7c8

Background Observer Query in App Delegate
 
 
Q