-2

I wrote this code to get heart rate I am using NSArray and getting average of heart rate. Now the question is the Apple Watch is updating data in Health Kit and I want the updated average heart beats being refreshed at every 1 minutes. I am stuck at this point, please help?

-(double)get_heartRates
{

//code to get the updated heart beats
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);


return avg_heartBeats;


//todo:- to get background update fast and easy

}

1 Answers1

0

Use HKObserverQuery to get a long running query that is updated in background:

https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKObserverQuery_Class/index.html

As long as no HKWorkoutSessionis running, your watch measures the heart rate every 10 minutes, so you don't get more values. When a HKWorkoutSession is running on your watch, you get values more frequently.

If you want to dive into HKWorkoutSession, Allan has a detailed tutorial: https://developer.apple.com/videos/play/wwdc2015/203/

Gerd Castan
  • 6,275
  • 3
  • 44
  • 89