Understanding results from HKSourceQuery, or Sources in general

最后都变了- 提交于 2019-12-10 11:42:14

问题


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:


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];


来源:https://stackoverflow.com/questions/29312686/understanding-results-from-hksourcequery-or-sources-in-general

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!