Search code examples
swifthealthkitios9.3

How to speed up HKStatisticsCollectionQuery in iOS 9.3?


It seems HKStatisticsCollectionQuery is incredibly slow in iOS 9.3. It can take upwards of 40 seconds to return hourly statistics for a year for active calories where it took 1 or less before.

let predicate = HKQuery.predicateForSamplesWithStartDate(anchorDate, endDate: endDate, options: [])
    let query = HKStatisticsCollectionQuery(quantityType: quantityType,
        quantitySamplePredicate: predicate,
        options: statisticOptions,
        anchorDate: anchorDate,
        intervalComponents: interval)

Solution

  • After many hours of trial and error I have found that HKStatisticsCollectionQuery is not thread friendly. In order to solve the problem I used this async NSOperation: https://gist.github.com/calebd/93fa347397cec5f88233

    And of course an NSOperationQueue in order to force the HKStatisticsCollectionQuerys to be performed synchronously. Once I did that each query took less than half a second.