ios - 如何按小时对 HKStatistics 进行分组?

标签 ios ios8 healthkit hksamplequery

我正在尝试从 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/

相关文章:

xcode - localizable.string 不适用于 iOS 8 中的模拟器

swift - iOS8 键盘扩展 clipsToBounds

ios - 判断 Health Kit 样本是否来自 Apple Watch?

ios - 如果你用的是Apple Watch,是否需要先打开Health App同步数据,然后再打开自己的healthkit app获取最新数据?

启动应用程序时出现 iOS 10.1 警告

ios - Spotify 搜索目录请求 : 400 Bad request

scroll - UITextView setText 不应该在 ios8 中跳到顶部

ios - 如何在 iOS Xcode UI 测试用例中启动系统应用程序

ios - JSON 写入错误 - 处理自定义类时类型无效

ios - 将 UIApplication.shared.isIdleTimerDisabled 设置为 false 时屏幕变暗