Clement Prem
Clement Prem

Reputation: 3119

HKSampleQuery is not retrieving the latest steps

I am using the following query to retrieve steps for a particular day using healthkit

//Predicate
NSDate *startDate = [[NSCalendar currentCalendar] startOfDayForDate:[NSDate date]];
NSDateComponents *comp = [NSDateComponents new];
comp.day = 1;
comp.second = -1;
NSDate *endDate = [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:startDate options: 0];
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:[[NSDate date] dateByAddingDays:endDate] options: HKQueryOptionStrictEndDate];


NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierStartDate ascending:YES];

HKQuantityType *type = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];


HKSampleQuery *stepsQuery = [[HKSampleQuery alloc] initWithSampleType: type
                                                                predicate: predicate limit:HKObjectQueryNoLimit
                                                          sortDescriptors:@[timeSortDescriptor]
                                                           resultsHandler: ^(HKSampleQuery *query, NSArray *resultsSteps, NSError *error) {
    }....

The issue: Latest steps are not returned by the query. There are two way I can get the latest steps

  1. Open the health app before opening my app - This will update the latest steps in the health app & the above query returns the latest steps
  2. Opening the app after 20-30 min it shows the latest steps

Am I missing something?

P.S It is a legacy code base so no Swift :)

Upvotes: 2

Views: 371

Answers (1)

Clement Prem
Clement Prem

Reputation: 3119

Adding an observer query below the sample query fixes the problem, I still couldn't find the root cause of this issue

 HKObserverQuery *ibsQuery  = [[HKObserverQuery alloc] initWithSampleType:steps predicate:pred updateHandler:^(HKObserverQuery * _Nonnull query, HKObserverQueryCompletionHandler  _Nonnull completionHandler, NSError * _Nullable error) {
        //Required completion block
    }];
 [healthStore executeQuery:ibsQuery];

Upvotes: 1

Related Questions