KAREEM MAHAMMED KAREEM MAHAMMED - 1 month ago 17
iOS Question

How to make multiple HKSampleQuery efficient way in Health Kit iOS

In my application integrated HealthKit Framework.

I want to get few Identifiers of HealthKit Data which is around 25.

As of my knowledge i have to fetch each Identifer like below

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

I have to wrote around 25 calls or i have to call them in for loop.

Is there any way we can call them either combine Queries or any efficient way.

Thank you in Advance.

Answer

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.