面试题答案
一键面试定义数据类型
在Objective-C中,HealthKit使用HKQuantityType
来表示各种健康数据类型。心率变异性(HRV)数据通常以毫秒(ms)为单位,属于数值类型。我们可以这样定义获取HRV数据所需的类型:
HKObjectType *hrvType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRateVariabilitySDNN];
这里HKQuantityTypeIdentifierHeartRateVariabilitySDNN
是HealthKit中用于心率变异性(SDNN,标准偏差)的标识符。
获取数据
- 授权:首先,需要获取用户对HRV数据的读取权限。
HKHealthStore *healthStore = [[HKHealthStore alloc] init];
NSArray<HKObjectType *> *typesToRead = @[hrvType];
[healthStore requestAuthorizationToShareTypes:nil readTypes:[NSSet setWithArray:typesToRead] completion:^(BOOL success, NSError * _Nullable error) {
if (!success || error) {
NSLog(@"授权失败: %@", error);
return;
}
// 授权成功,继续获取数据
}];
- 查询数据:授权成功后,可以查询HRV数据。
NSDate *startDate = [NSDate dateWithTimeIntervalSinceNow: - 24 * 60 * 60]; // 过去24小时
NSDate *endDate = [NSDate date];
HKQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:hrvType
quantitySamplePredicate:[HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone]
options:HKStatisticsOptionDiscreteAverage
completionHandler:^(HKStatisticsQuery * _Nonnull query, HKStatistics * _Nullable result, NSError * _Nullable error) {
if (result) {
HKQuantity *averageHRV = [result averageQuantity];
double hrvValue = [averageHRV doubleValueForUnit:[HKUnit secondUnit].unitDividedByUnit:[HKUnit unitWithString:@"1000"]];
NSLog(@"平均HRV: %f ms", hrvValue);
} else {
NSLog(@"查询错误: %@", error);
}
}];
[healthStore executeQuery:query];
上述代码查询过去24小时的平均HRV数据,并将其转换为毫秒输出。
处理数据更新的逻辑
- 注册更新通知:为了在HRV数据有更新时收到通知,可以使用
HKObserverQuery
。
HKObserverQuery *observerQuery = [[HKObserverQuery alloc] initWithSampleType:hrvType predicate:nil updateHandler:^(HKObserverQuery * _Nonnull query, HKObserverQueryCompletionHandler _Nonnull completionHandler, NSError * _Nullable error) {
if (!error) {
NSLog(@"HRV数据有更新");
// 在这里可以重新执行数据查询操作,以获取最新数据
// 例如,重新执行上述获取数据的查询
} else {
NSLog(@"观察错误: %@", error);
}
completionHandler();
}];
[healthStore executeQuery:observerQuery];
当HRV数据有更新时,updateHandler
会被调用,在这个块中可以重新查询最新的数据。这样就实现了对HRV数据更新的监听和处理。