Search code examples
iosswifthealthkitwatchos

Read Blood group, Age, Gender etc from HealthKit in Swift


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

As per Apple Doc here:

HealthKit provides five characteristic types: biological sex, blood type, birthdate, Fitzpatrick skin type, and wheelchair use. These types are used only when asking for permission to read data from the HealthKit store.

But i can't make add HKCharacteristicType in authorisation request.

I have run Apple Sample Project which requests for:

HKQuantityTypeIdentifier.stepCount.rawValue,
HKQuantityTypeIdentifier.distanceWalkingRunning.rawValue,
HKQuantityTypeIdentifier.sixMinuteWalkTestDistance.rawValue

But when I add

HKCharacteristicTypeIdentifier.bloodType.rawValue
HKCharacteristicTypeIdentifier.dateOfBirth.rawValue

The permission screen does not asks for DOB and Blood Type. See Image:

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.


Solution

  • 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)!
            ]
        }