Search code examples
iosobjective-chealthkithkhealthstorehksamplequery

Efficiently parse HKSampleQuery results for HealthKit on iOS


My app uses the HealthKit framework to retrieve user health data. I want to get around 25 different data points from HealthKit.

To do this, I currently have the 25 calls in a for-loop inside the completion handler for the sample query. Is there any way to combine the results, or do this process more efficiently?.

To my knowledge, this is how I have to do it (see code below). Thank you in advance.

NSDate *startDate, *endDate;

// Use the sample type for step count
HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

// Create a predicate to set start/end date bounds of the query
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];

// Create a sort descriptor for sorting by start date
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:YES];

HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:@[sortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
    if (!error && results) {
          for (HKQuantitySample *samples in results) {
              // your code here
           }
    }
}];

// Execute the query
[healthStore executeQuery:sampleQuery];

Solution

  • You should perform your queries parallel. This enables HealthKit to perform your queries efficiently. HealthKit does the optimization for you if you do it this way. The most elegant and readable way to do this is probably a loop. But writing 25 lines does the same.

    You don't need to do anything to get you queries into a background queue. HealthKit does this for you.

    Some times later you'll get your 25 callbacks.