我能够在健康应用中读取写样本数据,如身体质量,身高,体重,并从年龄,性别,血型等资料中读取.我的代码请求身份验证和读/写方法如下.
- (void)requestAuthorization { if ([HKHealthStore isHealthDataAvailable] == NO) { // If our device doesn't support HealthKit -> return. return; } HKObjectType *dateOfBirth = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth]; HKObjectType *bloodType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBloodType]; HKObjectType *biologicalSex = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex]; HKObjectType *wheelChairUse = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierWheelchairUse]; HKObjectType *skinType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierFitzpatrickSkinType]; HKObjectType *bodyMassIndex = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMassIndex]; HKObjectType *height = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight]; HKObjectType *bodyMass = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass]; HKObjectType *activeEnergy = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned]; HKObjectType *heartRate = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate]; HKObjectType *bloodGlucose = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBloodGlucose]; HKObjectType *bodyTemprature = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyTemperature]; HKObjectType *respiratoryRate = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierRespiratoryRate]; HKObjectType *oxygenSaturation = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierOxygenSaturation]; HKObjectType *fatPercentage = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyFatPercentage]; HKObjectType *waistCircumference = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierWaistCircumference]; HKObjectType *cholestrol = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryCholesterol]; NSArray *healthKitTypesToWrite = @[bodyMassIndex,activeEnergy,HKObjectType.workoutType]; NSArray *healthKitTypesToRead = @[dateOfBirth,bloodType,biologicalSex,bodyMassIndex,height,bodyMass,wheelChairUse,skinType,heartRate,bloodGlucose,bodyTemprature,respiratoryRate,oxygenSaturation,fatPercentage,waistCircumference,cholestrol,HKObjectType.workoutType]; [self.healthStore requestAuthorizationToShareTypes:[NSSet setWithArray:healthKitTypesToWrite] readTypes:[NSSet setWithArray:healthKitTypesToRead] completion:^(BOOL success,NSError * _Nullable error) { }]; }
pragma mark-助手
- (void )getMostRecentSampleForType:(HKSampleType *)sampleType withResultHandler:(HKQueryResultHandler )handler { NSPredicate *mostRecentPredicate = [HKQuery predicateForSamplesWithStartDate:NSDate.distantPast endDate:[NSDate date] options:HKQueryOptionStrictEndDate]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierStartDate ascending:false]; NSInteger limit = 1; HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:mostRecentPredicate limit:limit sortDescriptors:@[sortDescriptor] resultsHandler:^(HKSampleQuery * _Nonnull query,NSArray<__kindof HKSample *>* _Nullable results,NSError * _Nullable error) { dispatch_async(dispatch_get_main_queue(),^{ // do work here if (handler) { if (results && results.count > 0) { HKQuantitySample *sample = (HKQuantitySample *)[results firstObject]; handler(sample,nil); }else { handler(nil,error); } } }); }]; HKHealthStore *store = [[HKHealthStore alloc] init]; [store executeQuery:sampleQuery]; }
pragma mark-读取方法
- (NSDate *)readBirthDate { NSError *error; NSDateComponents *components = [self.healthStore dateOfBirthComponentsWithError:&error]; // Convenience method of HKHealthStore to get date of birth directly. NSCalendar *cal = [NSCalendar currentCalendar]; [cal setTimeZone:[NSTimeZone localTimeZone]]; [cal setLocale:[NSLocale currentLocale]]; NSDate *dateOfBirth = [cal dateFromComponents:components]; if (!dateOfBirth) { NSLog(@"Either an error occured fetching the user's age information or none has been stored yet. In your app,try to handle this gracefully."); } return dateOfBirth; } - (NSString *)biologicalSex { HKBiologicalSexObject *genderObj = [self.healthStore biologicalSexWithError:nil]; HKBiologicalSex gender = genderObj.biologicalSex; switch (gender) { case HKBiologicalSexNotSet: return @""; case HKBiologicalSexFemale: return @"Female"; case HKBiologicalSexMale: return @"Male"; case HKBiologicalSexOther: return @"Other"; default: break; } return @""; } - (NSString *)weight { HKSampleType *weightSampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass]; [self getMostRecentSampleForType:weightSampleType withResultHandler:^(HKQuantitySample *sample,NSError *error) { if (!errno) { HKQuantity *quantity = sample.quantity; HKUnit *kilogramUnit = [HKUnit gramUnitWithMetricPrefix:HKMetricPrefixKilo]; double weight = [quantity doubleValueForUnit:kilogramUnit]; NSLog(@"weight = %.0f Kg",weight); } }]; return @""; }
编译标记 – 写方法
- (void)writeWeightSample:(CGFloat)weight { // Each quantity consists of a value and a unit. HKUnit *kilogramUnit = [HKUnit gramUnitWithMetricPrefix:HKMetricPrefixKilo]; HKQuantity *weightQuantity = [HKQuantity quantityWithUnit:kilogramUnit doubleValue:weight]; HKQuantityType *weightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass]; NSDate *now = [NSDate date]; // For every sample,we need a sample type,quantity and a date. HKQuantitySample *weightSample = [HKQuantitySample quantitySampleWithType:weightType quantity:weightQuantity startDate:now endDate:now]; [self.healthStore saveObject:weightSample withCompletion:^(BOOL success,NSError *error) { if (!success) { NSLog(@"Error while saving weight (%f) to Health Store: %@.",weight,error); } }]; }
但我没有找到任何线索如何在Health Data-> Health Records中添加记录
解决方法
Apple正在使用此部分显示使用CDA文件检索的数据. CDA是一种允许医疗服务提供者之间互操作的标准.您可能能够从您的医疗服务提供者患者门户网站下载您自己的CDA.
没有很多应用程序会将CDA文件导入HealthKit,但apple有一个代码示例,它将创建一个虚拟CDA文件并将其导入HealthKit
从app查看LoopHealth示例
https://developer.apple.com/library/content/samplecode/LoopHealth/Introduction/Intro.html#//apple_ref/doc/uid/TP40017553-Intro-DontLinkElementID_2