Apple HealthKit葡萄糖水平读数给出了转换错误

时间:2017-03-20 08:15:34

标签: ios swift health-kit

我面临以下错误代码。下面的代码是Apple Health kit读取HealthApp的葡萄糖水平。

func updateGluco(){

let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose)
self.healthManager?.readMostRecentSample(sampleType, completion: {(mostRecentGluco, error) -> Void in

    if (error != nil){
        println("Error reading blood glucose from HealthKit store: \(error.localizedDescription)")
        return;
    }

    var glucoLocalizedString = self.kUnknownString;
    self.gluco = mostRecentGluco as? HKQuantitySample
    println("\(self.gluco?.quantity.doubleValueForUnit(HKUnit.moleUnitWithMolarMass(HKUnitMolarMassBloodGlucose)))")
    self.gluco?.quantity.doubleValueForUnit(HKUnit.moleUnitWithMolarMass(HKUnitMolarMassBloodGlucose))
    if let mmol = self.gluco?.quantity.doubleValueForUnit(HKUnit.moleUnitWithMolarMass(HKUnitMolarMassBloodGlucose)) {
        glucoLocalizedString = "\(mmol)"
    } else {
        println("error reading gluco data!")
    }
    dispatch_async(dispatch_get_main_queue(), {() -> Void in
    self.glucoLabel.text = glucoLocalizedString})
})

}

' NSInvalidArgumentException',原因:'尝试转换不兼容的单位:mg / dL,mol< 180.1558800000541>'

此行self.gluco?.quantity.doubleValueForUnit(HKUnit.moleUnitWithMolarMass(HKUnitMolarMassBloodGlucose))

1 个答案:

答案 0 :(得分:2)

您尝试进行的转换无效。您无法将质量/体积(mg/dL)数量转换为仅摩尔质量(mol)。尝试转换mg/dL - > mmol/L(每升毫摩尔),这是血糖测量的有效且常见的转换。

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