问题描述
我正在尝试从Healthkit读取Heartrate数据。我无法读取该数据。我已经完成了这个。
I am trying to read Heartrate data from Healthkit. I am not able to read that data. I have gone throught this link.
请帮帮我们..谢谢。
推荐答案
我设法使用HKSampleQuery从HelathKit读取心率。我从一天开始直到现在开始阅读。我也使用了这个
这是我的功能和我通过按下按钮来调用它:
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
以下是我打电话给函数在我的按钮操作中,它读取心率并将它们放入UITextView:
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;
}];
}
希望有所帮助。
这篇关于如何从Apple的Healthkit获取Heartrate数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!