【问题标题】:Efficiently parse HKSampleQuery results for HealthKit on iOS高效解析 iOS 上 HealthKit 的 HKSampleQuery 结果
【发布时间】:2016-10-28 07:27:28
【问题描述】:

我的应用使用 HealthKit 框架来检索用户健康数据。我想从 HealthKit 中获取大约 25 个不同的数据点。

为此,我目前在示例查询的完成处理程序中的 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];

【问题讨论】:

    标签: ios objective-c healthkit hkhealthstore hksamplequery


    【解决方案1】:

    您应该并行执行查询。 这使 HealthKit 能够有效地执行您的查询。 如果您这样做,HealthKit 会为您进行优化。 最优雅、最易读的方法可能是循环。 但是写 25 行也是一样的。

    您无需执行任何操作即可将查询放入后台队列。 HealthKit 会为您完成这项工作。

    一段时间后,您会收到 25 次回调。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多