我目前在今年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];
}
为什么我的查询没有返回任何数据?
答案 0 :(得分:0)
我终于弄清楚了几个小时后拉着我的头发试图理解为什么我的查询都没有被执行。我必须在我的所有代码之前添加以下内容:
if ([HKHealthStore isHealthDataAvailable]) {
self.healthStore = [[HKHealthStore alloc] init];
// Rest of my code below
//get the heart rates
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:now];
...
我还将我的[[dcs sharedContext] .healthStore]替换为我作为属性添加到我的VC的另一个healthstore实例。我会在Apple推荐的时候把它变成单身,但是现在这个修复工作正常。