HKAnchoredQuery update handler not working properly

那年仲夏 提交于 2019-12-02 17:41:40

问题


I wrote a code to get heart rate values from Health kit. The code is working fine but when the new heart values are updated in Health kit. I have to come to main screen and then multitask my app to get the updated results. What my aim is to get the updated result on my app without reopening or multitasking it, please help as I am new to iOS development. My code:-

  -(void)get_heartRates
{

//code to get the updated heart beats

HKSampleType *sampleType =
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];

HKObserverQuery *query =
[[HKObserverQuery alloc]
 initWithSampleType:sampleType
 predicate:nil
 updateHandler:^(HKObserverQuery *query,
                 HKObserverQueryCompletionHandler completionHandler,
                 NSError *error) {

     if (error) {


         NSLog(@"error occured while setting observer. %@ ",
               error.localizedDescription);
         abort();
     }

     // Take whatever steps are necessary to update your app's data and UI
     // This may involve executing other queries


     [self executeAnchoredQuery];

     // If you have subscribed for background updates you must call the completion handler here.
     // completionHandler();

 }];

[self.healthStore executeQuery:query];
 }

-(void)executeAnchoredQuery
{

NSDate *startDate1 = [NSDate distantPast];
NSPredicate *Predicate = [HKQuery     predicateForSamplesWithStartDate:startDate1 endDate:[NSDate date] options:HKQueryOptionStrictEndDate];
HKSampleType *object = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];

sum_Of_HeartRates=0.0;

HKAnchoredObjectQuery  *heartQuery = [[HKAnchoredObjectQuery alloc] initWithType:object predicate:Predicate anchor:self.lastAnchor limit:0 resultsHandler:^(HKAnchoredObjectQuery *query, NSArray<HKSample *> *sampleObjects, NSArray<HKDeletedObject *> *deletedObjects, HKQueryAnchor *newAnchor, NSError *error) {

    NSLog(@"Sample counts:%ld",sampleObjects.count);
    for(int i=0;i<(int)sampleObjects.count;i++)
    {

        HKQuantitySample *sample = (HKQuantitySample *)[sampleObjects objectAtIndex:i];
        HKQuantity *quantity = sample.quantity;
        double bpm_Values= [quantity doubleValueForUnit:[HKUnit unitFromString:@"count/min"]];
        sum_Of_HeartRates=sum_Of_HeartRates+bpm_Values;

    }
    avg_heartBeats=sum_Of_HeartRates/(int)sampleObjects.count;
}];

[heartQuery setUpdateHandler:^(HKAnchoredObjectQuery *query, NSArray<HKSample *> *SampleArray, NSArray<HKDeletedObject *> *deletedObjects, HKQueryAnchor *Anchor, NSError *error) {

    HKQuantitySample *sample = (HKQuantitySample *)[SampleArray objectAtIndex:0];
    HKQuantity *quantity = sample.quantity;
    new_Updated_Data =[quantity doubleValueForUnit:[HKUnit unitFromString:@"count/min"]];
    NSLog(@"new quantity:%f",new_Updated_Data);
}];

[self.healthStore executeQuery:heartQuery];
NSLog(@"updated data %f",new_Updated_Data);


NSLog(@"%f", avg_heartBeats);

 }

回答1:


See if the following code could help you...

 HKSampleType *sampleType =
    [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];

    HKObserverQuery *query =
    [[HKObserverQuery alloc]
     initWithSampleType:sampleType
     predicate:nil
     updateHandler:^(HKObserverQuery *query,
                     HKObserverQueryCompletionHandler completionHandler,
                     NSError *error) {

         if (error) {


             NSLog(@"error occured while setting observer. %@ ",
                   error.localizedDescription);
             abort();
         }

         // Take whatever steps are necessary to update your app's data and UI
         // This may involve executing other queries


[self executeAnchoredQuery];

         // If you have subscribed for background updates you must call the completion handler here.
         // completionHandler();

     }];

    [self.healthStore executeQuery:query];

and then the function where you write you anchoredQuery code, this may give you an idea of the code flow :

-(void)executeAnchoredQuery
{
HKSampleType *sampleType =
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

HKAnchoredObjectQuery *query =
[[HKAnchoredObjectQuery alloc]
 initWithType:sampleType
 predicate:nil
 anchor:self.anchor
 limit:HKObjectQueryNoLimit
 resultsHandler:^(HKAnchoredObjectQuery * _Nonnull query,
                  NSArray<__kindof HKSample *> * _Nullable sampleObjects,
                  NSArray<HKDeletedObject *> * _Nullable deletedObjects,
                  HKQueryAnchor * _Nullable newAnchor,
                  NSError * _Nullable error) {

     if (error != nil) {
         // Add proper error handling here...
         NSLog(@"*** Unable to query for step counts: %@ ***",
               error.localizedDescription);
         abort();
     }

     // Process the results...
     self.anchor = newAnchor;

     for (HKQuantitySample *sample in sampleObjects) {
         [self addStepCountSample:sample];
     }

     for (HKDeletedObject *sample in deletedObjects) {
         [self removeStepCountSample:sample];
     }

     NSLog(@"Done!");
 }];

[self.healthStore executeQuery:query];

}

Please go through apple developer docs for further details.



来源:https://stackoverflow.com/questions/36277821/hkanchoredquery-update-handler-not-working-properly

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