How to get Heartrate data from Apple's Healthk

2019-06-13 16:04发布

问题:

I am trying to read Heartrate data from Healthkit. I am not able to read that data. I have gone throught this link.

Please help me guys..Thank you.

回答1:

I managed to read the heart rates from HelathKit using HKSampleQuery. I start reading it from the beginning of the day till 'now'. I also used this link
Here is my function and I call it by pressing a button:

- (void)readHeartRateWithCompletion:(void (^)(NSArray *results, NSError *error))completion {

    //get the heart rates
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:now];
    components.hour = 0;
    components.minute = 0;
    components.second = 0;

    NSDate *beginOfDay = [calendar dateFromComponents:components];
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:beginOfDay endDate:now options:HKQueryOptionStrictStartDate];

    HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
    NSSortDescriptor *lastDateDescriptor = [[NSSortDescriptor alloc]

                                            initWithKey:HKSampleSortIdentifierStartDate ascending:YES selector:@selector(localizedStandardCompare:)];
    NSArray *sortDescriptors = @[lastDateDescriptor];

    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:sortDescriptors resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error){
        if (!results) {
            NSLog(@"An error occured fetching the user's heartrate. The error was: %@.", error);
            abort();
        }

        dispatch_async(dispatch_get_main_queue(), ^{

            NSMutableArray *arrayHeartRate = [[NSMutableArray alloc]init];

            for (HKQuantitySample *sample in results) {
                double hbpm = [sample.quantity doubleValueForUnit:[HKUnit heartBeatsPerMinuteUnit]];
                [arrayHeartRate addObject:[NSNumber numberWithDouble:hbpm]];
            }

            if (completion != nil) {
                completion(arrayHeartRate, error);
            }
        });
    }];
    [self.healthStore executeQuery:query];
}

Here is the function to get the value per minute to heartrate:

@implementation HKUnit (HKManager)

+(HKUnit *)heartBeatsPerMinuteUnit{
    return [[HKUnit countUnit]unitDividedByUnit:[HKUnit minuteUnit]];
}

@end

Here is how I call the function in my button action, it reads the heartrates and put them into an UITextView:

- (IBAction)readHeartRateButtonPressed:(id)sender {
    [[GSHealthKitManager sharedManager]readHeartRateWithCompletion:
    ^(NSArray *results, NSError *error) {
        NSString *items = [results componentsJoinedByString:@"\n"];
        _heartRateText.text = items;
    }];
} 

Hope it helps.