如何按小时分组HKStatistics?

And*_*y M 2 ios ios8 healthkit hksamplequery

我正在尝试从HealthKit中提取步骤数据.

我想创建按小时分组的步骤数据摘要.目前,我可以提取所有所提供的时间范围之间的数据的样本NSPredicateHKSampleQuery.我还可以得到日期范围与之间的步数之和HKStatisticsQuery.

我要问的是,是否有办法按小时对样本或统计数据进行分组.在SQL中我会写这样的东西:

SELECT HOUR(date), SUM(steps) FROM healthkit WHERE date BETWEEN 'blah' AND 'blah' GROUP BY 1;

我是否真的需要24小时31次查询HKStatistics来编写按小时分组的最后一个步骤数据?因为这似乎效率很低,特别是如何resultsHandler实施.

spa*_*sas 9

您应该使用HKStatisticsCollectionQuery可以按时间间隔执行分组的位置.示例存根代码将是:

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];
Run Code Online (Sandbox Code Playgroud)

您可以在HKStatisticsCollectionQuery文档中阅读更多详细信息