Home > Enterprise >  Read Blood group, Age, Gender etc from HealthKit in Swift
Read Blood group, Age, Gender etc from HealthKit in Swift

Time:08-25

I am trying to read Personal Details (Blood group, Age, Gender) of Healthkit but unable to request for that.

As per Apple Doc here

Configuration: Simulator iOS 15.4 and Xcode 13.3

Anyone knows that if we can access Personal Data of HealthKit or not. Please help me out.

CodePudding user response:

You can only request read authorization for the HKCharacteristicTypes, not share authorization. Update your code to add these 2 data types only to the readDataTypes variable. Right now you are requesting both read & share for the characteristic types, which is why they are not appearing on the authorization sheet.

CodePudding user response:

This is happening because bloodType and dateOfBirth are of type HKCharacteristicType

when you call this, the compactMap operation will not include your types

    private static var allHealthDataTypes: [HKSampleType] {
        let typeIdentifiers: [String] = [
            HKQuantityTypeIdentifier.stepCount.rawValue,
            HKQuantityTypeIdentifier.distanceWalkingRunning.rawValue,
            HKQuantityTypeIdentifier.sixMinuteWalkTestDistance.rawValue,
            HKCharacteristicTypeIdentifier.bloodType.rawValue,
            HKCharacteristicTypeIdentifier.dateOfBirth.rawValue
        ]
        
        return typeIdentifiers.compactMap { getSampleType(for: $0) }
    }

check getSampleType:

func getSampleType(for identifier: String) -> HKSampleType? {
    if let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: identifier)) {
        return quantityType
    }
    
    if let categoryType = HKCategoryType.categoryType(forIdentifier: HKCategoryTypeIdentifier(rawValue: identifier)) {
        return categoryType
    }
    
    return nil
}

your types won't fall into any of these if let, so this function will return nil. You must change the code so you are able to use HKCharacteristicTypeIdentifier as well.

EDIT: An easy way to do this is changing the readDataTypes in HealthData class to:

    static var readDataTypes: [HKObjectType] {
        return allHealthDataTypes   [
            HKObjectType.characteristicType(forIdentifier: .dateOfBirth)!,
            HKObjectType.characteristicType(forIdentifier: .bloodType)!
        ]
    }
  • Related