1

似乎 HKStatisticsCollectionQuery 在 iOS 9.3 中速度非常慢。可能需要超过 40 秒的时间才能返回一年中的每小时活跃卡路里统计数据,而之前需要 1 或更少的时间。

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

2 回答 2

1

如果有人在执行较长的 HKStatisticsCollectionQuery 请求时遇到问题(几十秒或几分钟),请考虑您已为谓词和锚点设置了正确的日期。问题是 HealthKit 应该计算大量数据。

例如,您的目标是收集今天的数据:

let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate)
    let query = HKStatisticsCollectionQuery(quantityType: quantityType,
                                            quantitySamplePredicate: predicate,
                                            options: .cumulativeSum,
                                            anchorDate: anchorDate,
                                            intervalComponents: interval)

这里startDate是今天的开始,endDate是明天的开始,anchorDate是某一天的开始 - 在我的情况下它等于 endDate。

重要提示:如果你传递 nil 而不是谓词,HealthKit 将从一开始就收集所有数据,从而浪费你的时间。为什么明天的开始必须作为 endDate?原因是statisticsUpdateHandler。由于您已决定在 HealthKit 中收听数据更新,因此谓词的结束日期应该是未来,而不是 Date()。如果您不想使用 statisticsUpdateHandler,您可以将 endDate 设置为现在。

于 2022-01-05T12:54:17.280 回答
0

经过数小时的反复试验,我发现 HKStatisticsCollectionQuery 不是线程友好的。为了解决这个问题,我使用了这个异步 NSOperation: https ://gist.github.com/calebd/93fa347397cec5f88233

当然还有一个 NSOperationQueue 以强制 HKStatisticsCollectionQuerys 同步执行。一旦我这样做了,每个查询只用了不到半秒的时间。

于 2016-05-03T19:55:03.227 回答