Shailesh Prajapati
Shailesh Prajapati

Reputation: 41

How to use updateHandler with HKAnchoredObjectQuery in iOS?

In my application I want to fetch HealthKit data using HKAnchoredObjectQuery. I've written code which is returning added and deleted data but i want to set UpdateHandler with HKAnchoredObjectQuery so, when data added/deleted in HealthKit then I get notification in app.

-(void)AnchoredObjectQueryTest
{
    HKSampleType *sampleType1 =
    [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];

    HKAnchoredObjectQuery *query =
    [[HKAnchoredObjectQuery alloc]
     initWithType:sampleType1
     predicate:nil
     anchor: HKAnchoredObjectQueryNoAnchor
     limit:HKObjectQueryNoLimit
     resultsHandler:^(HKAnchoredObjectQuery * query,
                      NSArray<HKSample *> * sampleObjects,
                      NSArray<HKDeletedObject *> * deletedObjects,
                      HKQueryAnchor *newAnchor,
                      NSError * error) {

         if (error) {

             // Perform proper error handling here...
             NSLog(@"*** An error occured while performing the anchored object query. %@ ***",
                   error.localizedDescription);

             abort();
         }

       anchor = newAnchor;


         for (HKQuantitySample *sample in sampleObjects) {
             NSLog(@"Add : %@", sample);
         }

         for (HKDeletedObject *sample in deletedObjects) {
              NSLog(@"Delete : %@", sample);
         }


     }];


     [healthStore executeQuery:query];
}

Upvotes: 2

Views: 1192

Answers (1)

steve1951
steve1951

Reputation: 193

Instantiate and execute your HKAnchoredObjectQuery and it will run once, calling back to the block specified in the handler parameter.

Instantiate the query and set the updateHandler property on the query, then execute the query. The query runs the first time as before, calling back to the handler parameter you provided at instantiation; the query runs subsequently when results are added or deleted to the store and calls back to your updateHandler.

In my case, I use the same block for the handler parameter and the updateHandler property.

Upvotes: 3

Related Questions