Get total step count for every date in HealthKit

后端 未结 6 546
南笙
南笙 2020-11-29 06:13

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 star

6条回答
  •  一生所求
    2020-11-29 06:40

    I wrapped mine in a completion block (objective -c). I found what was best was to set the startDate for the query to todays date at midnight. Hope this helps, feel free to copy/paste to get started

    -(void)fetchHourlyStepsWithCompletionHandler:(void (^)(NSMutableArray *, NSError *))completionHandler {
         NSMutableArray *mutArray = [NSMutableArray new];
         NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
    
         NSDate *startDate = [calendar dateBySettingHour:0 minute:0 second:0 ofDate:[NSDate date] options:0];
    
         NSDate *endDate = [NSDate date]; // 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:startDate endDate:endDate options:HKQueryOptionStrictStartDate];
    
         HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:type quantitySamplePredicate:predicate options:HKStatisticsOptionCumulativeSum anchorDate:startDate intervalComponents:intervalComponents];
    query.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection *results, NSError *error) {
        [results enumerateStatisticsFromDate:startDate toDate:endDate
         withBlock:^(HKStatistics *result, BOOL *stop) {
             if (!result) {
                 if (completionHandler) {
                     completionHandler(nil, error);
                 }
                 return;
             }
             
             HKQuantity *quantity = result.sumQuantity;
             
             NSDate *startDate = result.startDate;
           
             NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
             formatter.dateFormat = @"h a";
            
             NSString *dateString = [formatter stringFromDate:startDate]; 
             
             double steps = [quantity doubleValueForUnit:[HKUnit countUnit]];
             
             NSDictionary *dict = @{@"steps" : @(steps),
                                    @"hour" : dateString
                                    };
             
             [mutArray addObject:dict];
         }];
        
        if (completionHandler) {
            completionHandler(mutArray, error);
        }
    };
        [self.healthStore executeQuery:query];
    }
    

提交回复
热议问题