我正在尝试从Healthkit读取心率数据。我无法读取这些数据。我已经浏览了这个链接。
我使用HKSampleQuery从HelathKit读取心率。我从一天开始读到"现在"。我还使用了这个链接
这是我的函数,我通过按一个按钮调用它:
- (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;
}];
}
希望能有所帮助。