如何从Apple的Healthkit获取Heartrate数据?

时间:2015-09-12 12:25:45

标签: objective-c ios8 health-kit heartbeat

我正在尝试从Healthkit读取Heartrate数据。我无法读取该数据。我已经完成了link

请帮帮我们..谢谢。

1 个答案:

答案 0 :(得分:3)

我设法使用HKSampleQuery从HelathKit读取心率。我从一开始就开始阅读,直到现在#39;我也使用了这个link
这是我的功能,我按下按钮即可调用它:

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

以下是让每分钟值达到心率的功能:

@implementation HKUnit (HKManager)

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

@end

以下是我在按钮操作中调用该函数的方法,它读取心率并将它们放入UITextView:

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

希望它有所帮助。