问题描述
获取HealthKit
中记录的每天总步数的最佳方法是什么.使用HKSampleQuery的initWithSampleType方法(见下文),我可以使用NSPredicate
设置查询的开始和结束日期,但是该方法返回一个每天包含多个HKQuantitySamples的数组.
What's the best way to get a total step count for every day recorded in HealthKit
.With HKSampleQuery's method initWithSampleType (see below) I can set a start and end date for the query using NSPredicate
, but the method returns an array with many HKQuantitySamples per day.
- (instancetype)initWithSampleType:(HKSampleType *)sampleType
predicate:(NSPredicate *)predicate
limit:(NSUInteger)limit
sortDescriptors:(NSArray *)sortDescriptors
resultsHandler:(void (^)(HKSampleQuery *query,
NSArray *results,
NSError *error))resultsHandler
我想我可以查询所有记录的步数并遍历数组并计算每天的总步数,但是我希望有一个更简单的解决方案,因为将有成千上万个HKSampleQuery对象.有没有办法让initWithSampleType每天返回总步数?
I guess I can query all recorded step counts and go through the array and calculate the total step count for each day, but I'm hoping for an easier solution as there will be thousands of HKSampleQuery objects. Is there a way to have initWithSampleType return a total step count per day?
推荐答案
您应使用:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *interval = [[NSDateComponents alloc] init];
interval.day = 1;
NSDateComponents *anchorComponents = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
fromDate:[NSDate date]];
anchorComponents.hour = 0;
NSDate *anchorDate = [calendar dateFromComponents:anchorComponents];
HKQuantityType *quantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
// Create the query
HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType
quantitySamplePredicate:nil
options:HKStatisticsOptionCumulativeSum
anchorDate:anchorDate
intervalComponents:interval];
// Set the results handler
query.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection *results, NSError *error) {
if (error) {
// Perform proper error handling here
NSLog(@"*** An error occurred while calculating the statistics: %@ ***",error.localizedDescription);
}
NSDate *endDate = [NSDate date];
NSDate *startDate = [calendar dateByAddingUnit:NSCalendarUnitDay
value:-7
toDate:endDate
options:0];
// Plot the daily step counts over the past 7 days
[results enumerateStatisticsFromDate:startDate
toDate:endDate
withBlock:^(HKStatistics *result, BOOL *stop) {
HKQuantity *quantity = result.sumQuantity;
if (quantity) {
NSDate *date = result.startDate;
double value = [quantity doubleValueForUnit:[HKUnit countUnit]];
NSLog(@"%@: %f", date, value);
}
}];
};
[self.healthStore executeQuery:query];
这篇关于在HealthKit中获取每个日期的总步数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!