Search code examples
iosobjective-chealthkit

How do I construct a HealthKit HKUnit for mmol/L (millimoles per liter) for Blood Glucose values?


Blood glucose values were added back in Health in iOS 8.2: https://support.apple.com/en-us/HT203113

How do I construct a HealthKit HKUnit for mmol/L (millimoles per liter) for Blood Glucose values?

The following both throw exceptions: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse factorization string...

HKUnit *mmolPerL = [HKUnit unitFromString:@"mmol<molar mass>/L"];
HKUnit *mmolPerL = [HKUnit unitFromString:@"mmol/L"];

Solution

  • Can confirm that the examples provided don't work (every permutation), the alternative mg/dL unit does.

    To sum up, both proposed approaches work, with similar (with the approach proposed by @cbartel the constant is actually rounded, not with the other) results regarding to the structure of the resulting HKUnit:

    Printing description of mmolPerL->_baseUnits->_factors:
    NSMapTable {
    [6] mmol<180.15588> -> 1
    [7] L -> -1
    }
    

    I'd use the shorter form using the provided constant:

    HKUnit *mmolPerL = [HKUnit unitFromString:[NSString stringWithFormat:@"mmol<%f>/L",HKUnitMolarMassBloodGlucose]];