我正在尝试从 HealthKit 中提取步数数据。
我想创建按小时分组的步数数据摘要。目前,我可以使用 HKSampleQuery
提取 NSPredicate
提供的日期范围内的所有数据样本。我还可以使用 HKStatisticsQuery
获取某个日期范围内的步数总和。
我想问的是,是否有一种方法可以按小时对样本或统计数据进行汇总分组。在 SQL 中,我会这样写:
SELECT HOUR(date), SUM(steps) FROM healthkit WHERE date BETWEEN 'blah' AND 'blah' GROUP BY 1;
我是否真的需要 24 x 31 次查询 HKStatistics 才能写入按小时分组的最后一个月的步骤数据?因为这看起来效率很低,尤其是 resultsHandler
的实现方式。
最佳答案
您应该使用 HKStatisticsCollectionQuery
,您可以在其中按时间间隔执行分组。一个示例 stub 代码是:
NSDate *startDate, *endDate, *anchorDate; // Whatever you need in your case
HKQuantityType *type = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
// Your interval: sum by hour
NSDateComponents *intervalComponents = [[NSDateComponents alloc] init];
intervalComponents.hour = 1;
// Example predicate
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:fromDate endDate:toDate options:HKQueryOptionStrictStartDate];
HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:type quantitySamplePredicate:predicate options:HKStatisticsOptionCumulativeSum anchorDate:anchorDate intervalComponents:intervalComponents];
query.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection *result, NSError *error) {
// do something with the results
};
[healthStore executeQuery:query];
您可以在 HKStatisticsCollectionQuery docs 中阅读更多详细信息
关于ios - 如何按小时对 HKStatistics 进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26299185/