【问题标题】:Trouble Retrieving Heart Rate Data from HealthKit从 HealthKit 检索心率数据时遇到问题
【发布时间】:2017-03-14 17:31:39
【问题描述】:

我目前在我的健康应用程序中存储了今年 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];
}

为什么我的查询没有返回任何数据?

【问题讨论】:

    标签: ios objective-c xcode healthkit hksamplequery


    【解决方案1】:

    经过数小时拉头发试图理解为什么我的查询没有被执行后,我终于弄明白了。我必须在所有代码之前添加以下内容:

    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];
    ...
    

    我还用另一个 healthstore 实例替换了我的 [[dcs sharedContext].healthStore],该实例是我作为属性添加到我的 VC 中的。稍后我将按照 Apple 的建议将其变成单例,但目前此修复程序有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多