簡體   English   中英

我可以繼續閱讀HealthKit的步驟嗎?

[英]Can I keep reading steps with HealthKit?

目的是在用戶執行所需步驟時觸發一種方法。 這是我的代碼:

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:用於停止長時間運行的查詢。

我認為這兩點才是真正重要的。

有可能達到目的嗎? 如果是這樣,我該如何解決?

在循環中,必須在調用executeQuery:之前創建一個新的HKSampleQuery 您不能重用HKQuery實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM