Search code examples
iosobjective-ciphonehealthkithksamplequery

Can I keep reading steps with HealthKit?


The purpose is trigger a method when the user walks the required steps. here is my code:

if ([HKHealthStore isHealthDataAvailable]) {
        self.healthStore = [[HKHealthStore alloc] init];
        NSSet *stepsType =[NSSet setWithObject:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]];
        [self.healthStore requestAuthorizationToShareTypes:nil readTypes:stepsType completion:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                __block double stepsCount = 0.0;
                HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
                HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:nil limit:HKObjectQueryNoLimit sortDescriptors:nil resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
                    if (!error && results>0) {
                        for (HKQuantitySample *result in results) {
                            stepsCount += [result.quantity doubleValueForUnit:[HKUnit countUnit]];
                        }
                    }
                }];
                [self.healthStore executeQuery:sampleQuery];
                double currentSteps = stepsCount;
                while (1) {
                    [self.healthStore stopQuery:sampleQuery];
                    [self.healthStore executeQuery:sampleQuery];
                    if (currentSteps + requiredSteps >= stepsCount) {
                        [self triggerOneMethod];
                        break;
                    }
                }
            }
        }];
    }

But when I run the app, Xcode shows:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: 'You cannot start a query that is already active'
***

I have read the HealthKit Document, it says that

HealthKit executes queries asynchronously on a background queue. Most queries automatically stop after they have finished executing.

and stopQuery: is to stop a long-running query.

I think these two points are what really matter.

Is it possible to achieve the purpose? If so, how can I fix it?


Solution

  • In the loop, you must create a new HKSampleQuery before calling executeQuery:. You cannot reuse an HKQuery instance.