gpt4 book ai didi

objective-c - 获取 HealthKit 中每个日期的总步数

转载 作者:太空狗 更新时间:2023-10-30 03:30:32 27 4
gpt4 key购买 nike

获取记录在 HealthKit 中的每一天的总步数的最佳方法是什么。通过 HKSampleQuery 的方法 initWithSampleType(见下文),我可以使用 NSPredicate 设置查询的开始和结束日期,但该方法每天返回一个包含许多 HKQuantitySamples 的数组。

- (instancetype)initWithSampleType:(HKSampleType *)sampleType
predicate:(NSPredicate *)predicate
limit:(NSUInteger)limit
sortDescriptors:(NSArray *)sortDescriptors
resultsHandler:(void (^)(HKSampleQuery *query,
NSArray *results,
NSError *error))resultsHandler

我想我可以查询所有记录的步数并遍历数组并计算每天的总步数,但我希望有一个更简单的解决方案,因为将有数千个 HKSampleQuery 对象。有没有办法让 initWithSampleType 返回每天的总步数?

最佳答案

你应该使用 HKStatisticsCollectionQuery :

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];

关于objective-c - 获取 HealthKit 中每个日期的总步数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29582462/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com