簡體   English   中英

如何按小時分組HKStatistics?

[英]How to group HKStatistics by hour?

我正在嘗試從HealthKit中提取步驟數據。

我想創建按小時分組的步驟數據摘要。 目前,我可以在NSPredicate提供的日期范圍與HKSampleQuery之間提取所有數據樣本。 我還可以使用HKStatisticsQuery日期范圍之間的步數總和。

我要問的是,是否有辦法按小時對樣本或統計數據進行分組。 在SQL中我會寫這樣的東西:

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

我是否真的需要24小時31次查詢HKStatistics來編寫按小時分組的最后一個步驟數據? 因為這看起來效率很低,特別是對於如何實現resultsHandler

您應該使用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];

您可以在HKStatisticsCollectionQuery文檔中閱讀更多詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM