swifthealthkitios14wwdc

How to get ECG Voltage Measurements HKElectrocardiogram.VoltageMeasurement iOS 14


I'm trying to get the individual voltage measurements of an ECG back from Apple HealthKit using new APIs in iOS 14.

I've already managed to use:

let ecgQuery = HKSampleQuery(sampleType: HKObjectType.electrocardiogramType(), predicate: samplePredicate, limit: 0, sortDescriptors: [sortDescriptor]){ (query, results, error) in

which gets me a HKElectrocardiogram object. From this I can see the average heart rate, ECG classification etc...

I now believe I need to pass that object into an HKElectrocardiogramQuery like this:

let ecgSample = HKElectrocardiogramQuery(ecg) { (query, result) in

but I can't find any way to extract data from the result data handler. If I put a print in on result, it executes many times but again, I can't extract the data. result is of type HKElectrocardiogramQuery.Result

The documentations pretty sketchy on Apple's developer site with zero examples provided. The capability is mentioned though in Apple's What's New In HealthKit talk from WWDC 2020. Any help would be very appreciated.

Cheers


Solution

  • Based on the available documentation, you have to switch over the result to get the measurement value

    let query = HKElectrocardiogramQuery(ecg) { (query, result) in
    
        switch result {
        case .error(let error):
            print("error: ", error)
            
        case .measurement(let value):
            print("value: ", value)
            
        case .done:
            print("done")
        }
    }
    
    store.execute(query)