了解HKSourceQuery或一般来源的结果

时间:2015-03-28 01:38:21

标签: ios swift health-monitoring health-kit hkhealthstore

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

如何使用它来使用HKQuery.predicateForObjectsFromSource(/* source goes here */)

创建谓词

1 个答案:

答案 0 :(得分:2)

以下是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为大多数HK类创建对象。
  2. 我相信您可以使用HKSource属性sourcesHKSource找到name集中的bundleIdentifier对象。
  3. 以下是示例代码

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