问题
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)
回答1:
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.
来源:https://stackoverflow.com/questions/36582705/how-to-speed-up-hkstatisticscollectionquery-in-ios-9-3