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

Mat*_*sMo 8 objective-c healthkit hksamplequery

什么是获得记录的每一天的总步数的最佳方法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
Run Code Online (Sandbox Code Playgroud)

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

nin*_*ger 16

你应该使用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];
Run Code Online (Sandbox Code Playgroud)


seb*_*anr 7

移植到Swift,不依赖于SwiftDate库

    let calendar = NSCalendar.current
    let interval = NSDateComponents()
    interval.day = 1

    var anchorComponents = calendar.dateComponents([.day, .month, .year], from: NSDate() as Date)
    anchorComponents.hour = 0
    let anchorDate = calendar.date(from: anchorComponents)

    // Define 1-day intervals starting from 0:00
    let stepsQuery = HKStatisticsCollectionQuery(quantityType: stepsCount!, quantitySamplePredicate: nil, options: .cumulativeSum, anchorDate: anchorDate!, intervalComponents: interval as DateComponents)

    // Set the results handler
    stepsQuery.initialResultsHandler = {query, results, error in
        let endDate = NSDate()
        let startDate = calendar.date(byAdding: .day, value: -7, to: endDate as Date, wrappingComponents: false)
        if let myResults = results{
            myResults.enumerateStatistics(from: startDate!, to: endDate as Date) { statistics, stop in
            if let quantity = statistics.sumQuantity(){
                let date = statistics.startDate
                let steps = quantity.doubleValue(for: HKUnit.count())
                print("\(date): steps = \(steps)")
                //NOTE: If you are going to update the UI do it in the main thread
                DispatchQueue.main.async {
                    //update UI components
                }

            }
            } //end block
        } //end if let
    }
    healthStore?.execute(stepsQuery)
Run Code Online (Sandbox Code Playgroud)