ios - 在进行查询时使用谓词过滤来源

标签 ios nspredicate healthkit

我正在尝试创建一个关于步数的 HKStatisticsQuery,其中的谓词会忽略用户输入的值。

我发现用户输入的值和被动记录的值之间存在 2 个差异:

来源:
- 被动记录值的来源为“A's iPhone”
- 用户输入的值的来源为“健康”

'Was User Entered'元数据键:
-被动记录根本没有元数据 key
- 用户输入的值将“Was User Entered”元数据键设置为 true

我试过这个谓词,试图只获取将“Was User Entered”设置为 false 的数据: HKQuery.predicateForObjectsWithMetadataKey(HKMetadataKeyWasUserEntered, allowedValues: [false])

我没有得到任何结果,有人帮助我意识到如果元数据 key 是被动记录的(有点多余...),它甚至不存在

鉴于上述差异,是否有人知道提取被动记录数据的任何其他方法?我在想

NSPredicate(format: "%K != %@", HKPredicateKeyPathSource, "Health")//崩溃

当我执行查询时,这个谓词不起作用并使我的程序崩溃。

有谁知道它崩溃的原因,或者是否有更好的方法来实现我清除用户输入的数据的目标?

谢谢。

最佳答案

您的崩溃可能是因为目前仅支持“=”和“IN”运算符用于按源过滤 HKSamples 的谓词

您可以首先使用源查询来提取所有源并忽略健康应用程序源(其包标识符为 com.apple.Health),方法是使用以下代码:

- (void)fetchSources 
{
    NSMutableArray *dataSources = [[NSMutableArray alloc] init];
    HKQuantityType *stepsCount = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    HKSourceQuery *sourceQuery = [[HKSourceQuery alloc] initWithSampleType:stepsCount
                                                           samplePredicate:nil
                                                         completionHandler:^(HKSourceQuery *query, NSSet *sources, NSError *error)
                                                         {
                                                             for (HKSource *source in sources)
                                                             {
                                                                 if (![source.bundleIdentifier isEqualToString:@"com.apple.Health"])
                                                                 {
                                                                     [dataSources addObject:source];
                                                                 }
                                                             }
                                                         }];
    [self.healthStore executeQuery:sourceQuery];
}

一旦您拥有除 Health App 之外的所有其他来源,请使用来源谓词为所有其他来源提取数据:

NSPredicate *sourcesPredicate = [HKQuery predicateForObjectsFromSources:[NSSet setWithArray:self.dataSources]]

希望这对您有所帮助。

关于ios - 在进行查询时使用谓词过滤来源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29311891/

相关文章:

ios - 调用 array.removeAll() 后 tableview.reload 不起作用 swift 5

iphone - 使用 nspredicate 进行快速研究

ios - NSPredicate 对象模型数组过滤器无法在 Swift 4.0 中崩溃

swift - HealthKit - 积累在 watchOS 4 中燃烧的能量

ios - 如何设置不是InterfaceController的HKWorkoutSessionDelegate

ios - NS正则表达式组(匹配项)

ios - 通过 UISwitch 启用推送通知

ios - WKWebView(beta)的takeSnapshot方法,如何实现?

ios - NSPredicate 参数过多。很难读懂

ios - Apple HealthKit - 后台更新未触发