我目前在我的健康应用程序中存储了今年 1 月初的两条心率记录。在我正在制作的当前应用程序中,我授予读取和写入心率数据的权限。
在我的视图控制器之一的 viewDidAppear 中,我正在尝试读取心率记录。但是,我没有成功检索任何数据。
这是我读取的心率数据代码:
+ (void)readHeartRateWithCompletion:(void (^)(NSArray *results, NSError *error))completion {
HKQuantityType *heartRateType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierStartDate ascending:YES];
NSDate *lastSample = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastTsUploaded"];
if (!lastSample) {
lastSample = [NSDate dateWithTimeIntervalSinceNow:-24 * 60 * 60];
}
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDate *now = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:now];
[comps setYear:[comps year] - 2];
NSDate *hundredYearsAgo = [gregorian dateFromComponents:comps];
NSPredicate *pred = [HKQuery predicateForSamplesWithStartDate:hundredYearsAgo endDate:[NSDate date] options:HKQueryOptionStrictStartDate];
HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:heartRateType predicate:pred limit:10 sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
if (!results) {
NSLog(@"There are no heart rate results. The error was: %@.", error);
return;
}
}];
[[dcsContext sharedContext].healthStore executeQuery:sampleQuery];
}
为什么我的查询没有返回任何数据?