ios - 了解 HKSourceQuery 或一般来源的结果

标签 ios swift health-monitoring healthkit hkhealthstore

我刚刚做了一个 HKSourceQuery 并得到了一些结果。当我做println时在结果中,我得到了这个:<HKSource:0x156c1520 "Health" (com.apple.Health)>//description of the object

我如何使用它来使用 HKQuery.predicateForObjectsFromSource(/* source goes here */) 来创建谓词

最佳答案

这是 Obj-c 中的示例代码,

NSSortDescriptor *timeSortDesriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];

        HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
        HKSourceQuery *sourceQuery = [[HKSourceQuery alloc] initWithSampleType:quantityType samplePredicate:nil completionHandler:^(HKSourceQuery *query, NSSet *sources, NSError *error) {

            //Here, sources is a set of all the HKSource objects available for "quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned"

            HKSource *targetedSource = [[sources allObjects] firstObject];//Assume this as your targeted source
            if(targetedSource)
            {
                NSPredicate *sourcePredicate = [HKQuery predicateForObjectsFromSource:targetedSource];
                HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:quantityType predicate:sourcePredicate limit:HKObjectQueryNoLimit sortDescriptors:[NSArray arrayWithObject:timeSortDesriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
                   //results array contains the HKSampleSample objects, whose source is "targetedSource".
                }];
                [self.healthStore executeQuery:query];
            }
        }];
        [self.healthStore executeQuery:sourceQuery];

更新1:

  1. 无法构造HKSource使用 [HKSource alloc] init] 手动对象。在 HealthKit 框架中,Apple 使用 init 限制对象的创建对于大多数香港类(class)。
  2. 我相信您一定能找到您的HKSource来自 sources 的对象使用 HKSource 设置属性如 namebundleIdentifier .

这是示例代码,

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.source.bundleIdentifier = 'com.XXXX.XXXXX'"];
    NSArray  *tempResults = [[sources allObjects] filteredArrayUsingPredicate:predicate];

    HKSource *targetedSource = [tempResults firstObject];

关于ios - 了解 HKSourceQuery 或一般来源的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29312686/

相关文章:

ios - 当通过 UIRefreshControl 调用时,UITableView 重新加载会重复 NSMutableArray 的值

iphone - 如何将 NSString 的每个字符添加到 NSArray 中?

ios - 用户注销时清除钥匙串(keychain)中的值

java - 我们是否需要测试 cron 作业是否正在运行?或者是否需要 cron 作业的健康检查?

iOS UITableViewCell 附件无法正确显示(披露指示器除外)

ios - 如何解决可能出现意外的 Swift 警告 : "Constant ' value' inferred to have type 'AnyClass?' (aka 'Optional<AnyObject.Type>' ),?

xcode - 委托(delegate)协议(protocol)不起作用,返回 nil

json - 保存 json 响应并将其解析为 swift 对象

java - DropWizard 没有注册我的健康检查

ios - 从 iHealth 设备(ios - Swift)实时阅读?