我能够在健康应用程序中读取写入的示例数据,例如体重,高度,体重,并从年龄,性别,血液类型等配置文件数据中读取。下面给出了我的请求验证和读取/写入方法的代码段。

- (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) {

    }];
}

实用标记- helper
- (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];
}

实用标记-读取方法
- (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中的记录

objective-c - 如何通过Health Kit将Health Records添加到Health App-LMLPHP

objective-c - 如何通过Health Kit将Health Records添加到Health App-LMLPHP

最佳答案

Apple正在使用此部分显示使用CDA文件检索的数据。 CDA是允许健康提供者之间互操作性的标准。您很可能可以从医疗服务提供者的患者门户网站下载自己的CDA。

那里没有很多将CDA文件导入HealthKit的应用程序,但是Apple有一个代码示例,它将创建一个虚拟CDA文件并将其导入到HealthKit中。

从应用程序 checkout LoopHealth示例
https://developer.apple.com/library/content/samplecode/LoopHealth/Introduction/Intro.html#//apple_ref/doc/uid/TP40017553-Intro-DontLinkElementID_2

关于objective-c - 如何通过Health Kit将Health Records添加到Health App,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48701095/

10-13 03:57