Understanding results from HKSourceQuery, or Sourc

2019-06-03 15:08发布

I just did a HKSourceQuery and got some results. When I do a println of the results, I got this: <HKSource:0x156c1520 "Health" (com.apple.Health)>//description of the object

How do I use this to make a predicate using the HKQuery.predicateForObjectsFromSource(/* source goes here */)

1条回答
手持菜刀,她持情操
2楼-- · 2019-06-03 15:31

Here is the sample code in 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];

UPDATE 1:

  1. It is not possible to construct HKSource object manually using [HKSource alloc] init]. In HealthKit framework, Apple restricted creation of objects using init for most of the HK classes.
  2. I believe that you can find your HKSource object from the sources set using the HKSource properties like name and bundleIdentifier.

Here is the sample code,

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

    HKSource *targetedSource = [tempResults firstObject];
查看更多
登录 后发表回答