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: https://support.apple.com/en-us/HT203113

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"];

      

+3


source to share


5 answers


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

does.

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]];

      

+2


source


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



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

      

+7


source


The "molar mass" passed to the HKUnitFromString: must be a decimal value representing the molar mass of the substance ( http://en.wikipedia.org/wiki/Molar_mass ). 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"];

+2


source


Here's an example in Swift 4:

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

      

+1


source


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)

      

Example:

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

      

0


source