0

目的是在用户完成所需步骤时触发方法。这是我的代码:

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

但是当我运行应用程序时,Xcode 显示:

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

我已经阅读了 HealthKit 文档,它说

HealthKit 在后台队列上异步执行查询。大多数查询在完成执行后会自动停止。

并且stopQuery:是停止长时间运行的查询。

我认为这两点才是真正重要的。

有没有可能达到目的?如果是这样,我该如何解决?

4

1 回答 1

1

在循环中,您必须HKSampleQuery在调用之前创建一个新的executeQuery:。您不能重复使用 HKQuery 实例。

于 2016-02-05T00:06:56.203 回答