2016-10-28 63 views
3

我的應用使用HealthKit框架檢索用戶健康數據。我想要從HealthKit獲得25個不同的數據點。高效解析iOS上HealthKit的HKSampleQuery結果

要做到這一點,我現在有一個for-loop爲樣本查詢完成處理內部的25個電話。 有什麼方法可以將結果合併,或者更高效地完成此過程?

據我所知,這是我必須做的(見下面的代碼)。先謝謝你。

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

回答

3

您應該執行並行查詢。 這使HealthKit能夠高效地執行您的查詢。 如果您這樣做,HealthKit會爲您進行優化。 做這件事最優雅和可讀的方式可能是一個循環。 但寫25行也一樣。

你不需要做任何事情來讓你查詢到後臺隊列。 HealthKit爲您做到這一點。

有些時候,你會得到你的25回調。