Better way to run multiple HealthKit sample queries?

后端 未结 3 1521
花落未央
花落未央 2021-01-14 14:30

I have a scenario where I need to retrieve multiple sets of data from HealthKit -- body temperature, weight, and blood pressure. I need all 3 before I can continue processin

相关标签:
3条回答
  • 2021-01-14 14:50

    I ran into this same problem, and a much better approach for any kind of nested async call would be to use GCD's dispatch groups. These allow you to wait until multiple async tasks have completed.

    Here's a link with an example: Using dispatch groups to wait for multiple web services

    0 讨论(0)
  • 2021-01-14 14:54

    You should try to run the queries in parallel for better performance. In the completion handler for each one, call a common function that notes a query has completed. In that common function, when you determine that all of the queries have finished then you can proceed to the next step.

    One simple approach to tracking the completion of the queries in the common function is to use a counter, either counting up from zero to the number of queries, or down from the number of total queries to zero.

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

    0 讨论(0)
  • 2021-01-14 14:57

    You're going to want to use GCD dispatch groups.

    First, set up a global variable for the main thread

    var GlobalMainQueue: dispatch_queue_t {
      return dispatch_get_main_queue()
    }
    

    Next, create the dispatch group:

    let queryGroup = dispatch_group_create()
    

    Right before your queries execute, call:

    dispatch_group_enter(queryGroup)
    

    After your query executes, call:

    dispatch_group_leave(queryGroup)
    

    Then, handle your completion code:

    dispatch_group_notify(queryGroup, GlobalMainQueue) {
      // completion code here
    }
    
    0 讨论(0)
提交回复
热议问题