How to build HealthKit HKUnit for mmol / L (millimoles per liter) for blood glucose values?

Blood glucose values ​​have been added in Health in iOS 8.2:

How to build HealthKit HKUnit for mmol / L (millimoles per liter) for blood glucose values?

The following exceptions are: Application terminated due to an unmapped 'NSInvalidArgumentException', reason: 'Unable to parse the factorization string ...

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



source to share

5 answers

It can be confirmed that the examples given do not work (every permutation) the alternate block mg/dL


To summarize, both suggested approaches work with similar (with the approach suggested by @cbartel, the constant is actually rounded and not different) results regarding the structure of the resulting HKUnit:

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


I would use a shorter form using the provided constant:

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




Construct two HKUnits and then perform a math unit to create a complex unit:

HKUnit *mmolPerL = [[HKUnit moleUnitWithMetricPrefix:HKMetricPrefixMilli molarMass:HKUnitMolarMassBloodGlucose] unitDividedByUnit:[HKUnit literUnit]];




The "molar mass" passed to the HKUnitFromString: must be a decimal value representing the molar mass of the substance ( ). Blood glucose has a molar mass of ~ 180,156 (see HKUnitMolarMassBloodGlucose in HKUnit.h for a more precise value). To build this using single lines, you would like to use:

HKUnit * mmolPerL = [HKUnit unitFromString: @ "mmol <180,156> / L"];



Here's an example in Swift 4:

let mass = HKUnitMolarMassBloodGlucose
let mmolPerLiter = HKUnit.moleUnit(with: .milli, molarMass: mass).unitDivided(by: .liter())




In Swift 4:

let bloodGlucoseMgDlUnit = HKUnit.gramUnit(with: .milli).unitDivided(by: HKUnit.literUnit(with: .deci))
let bloodGlucoseMMolLUnit = HKUnit.moleUnit(with: .milli, molarMass: HKUnitMolarMassBloodGlucose).unitDivided(by: HKUnit.liter())

let mgdlValue = sample.quantity.doubleValue(for: bloodGlucoseMgDlUnit)
let mmollValue = sample.quantity.doubleValue(for: bloodGlucoseMMolLUnit)



81.0 mg/dL, 4.4961063718806 mmol/L
83.0 mg/dL, 4.6071213440258 mmol/L