What's the best way to run multiple HealthKit request examples?

I have a scenario where I need to get multiple datasets from HealthKit - body temperature, weight and blood pressure. I need all 3 before I can continue processing because they will end up in the PDF.

My naive first approach will run one and then in the results the HKSampleQueryHandler will call the second, and then in that resultsHandler will call the third one. It looks like - I don't know - it looks like I missed something.

Is there a better way or is the naive approach sane?

+3


source to share


3 answers


You should try to run queries in parallel for better performance. In the completion handler for each of them, call a generic function that marks the request complete. In this general function, when you determine that all requests are complete, you can proceed to the next step.

One simple approach to tracking the execution of requests in a shared function is to use a counter, either counting from zero to number of requests, or from number of requests to zero.



Since HealthKit request handlers are called on an anonymous background message queue, make sure you synchronize access to the counter by either securing it with a lock or changing the counter on a serial dispatch queue that you control, such as the main queue.

0


source


I ran into this same problem and for any nested asynchronous call, it would be much better to use GCD dispatch groups. This allows you to wait for multiple asynchronous tasks to complete.



Here is a link with an example: Using distribution groups to listen for multiple web services.

+5


source


You will want to use GCD send groups.

First, set up a global variable for the main thread

var GlobalMainQueue: dispatch_queue_t {
  return dispatch_get_main_queue()
}

      

Then create a dispatch group:

let queryGroup = dispatch_group_create()

      

Before executing your queries, call:

dispatch_group_enter(queryGroup)

      

After completing your request, call:

dispatch_group_leave(queryGroup)

      

Then process the completion code:

dispatch_group_notify(queryGroup, GlobalMainQueue) {
  // completion code here
}

      

+2


source







All Articles