Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"];
like image 602
cbartel Avatar asked May 11 '15 21:05

cbartel


2 Answers

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

HKUnit *mmolPerL = [[HKUnit moleUnitWithMetricPrefix:HKMetricPrefixMilli molarMass:HKUnitMolarMassBloodGlucose] unitDividedByUnit:[HKUnit literUnit]];
like image 100
cbartel Avatar answered Sep 22 '22 02:09

cbartel


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
like image 30
Nata Avatar answered Sep 18 '22 02:09

Nata