Swift读取Apple Health血糖数据:如何仅输出7.8 mmol数值?
Problem Description
I've obtained access to Apple Health and can read blood glucose data in the Simulator. Here's my implementation code:
guard let sampleType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose) else { fatalError("*** This method should never fail ***") } let query = HKSampleQuery(sampleType: sampleType, predicate: nil, limit: Int(HKObjectQueryNoLimit), sortDescriptors: nil) { query, results, error in guard let samples = results as? [HKQuantitySample] else { // Handle error return } for sample in samples { print(sample) } }
When I run this code, the output looks like this:
(2020-05-06 19:09:49 +0200 - 2020-05-06 19:09:49 +0200) 7.8 mmol<180.1558800000541>/L 811AACEB-F942-4A48-937B-568AD66E1BDE "Health" (13.3), "iPhone12,3" (13.3)metadata: { HKWasUserEntered = 1; }
I want to output only the 7.8 mmol value. I couldn't find relevant methods in Apple's official documentation, so I'm asking for help.
Solution
Hey, you don't need to parse that printed string at all! That's just the debug description of HKQuantitySample, which isn't reliable to parse (its format might change across iOS versions). HealthKit provides proper APIs to extract the exact value and unit you need.
Here's how to modify your loop to get and print just the blood glucose value in mmol/L:
for sample in samples { // Get the HKQuantity object from the sample let glucoseQuantity = sample.quantity // Define the unit we want: millimoles per liter for blood glucose let mmolUnit = HKUnit.moleUnit(with: .milli, molarMass: HKUnitMolarMassBloodGlucose) // Extract the numerical value in the specified unit let glucoseValue = glucoseQuantity.doubleValue(for: mmolUnit) // Format and print the result print("\(glucoseValue) mmol/L") }
How this works:
HKQuantitySamplehas aquantityproperty that holds the actual measurement value and its unit.HKUnit.moleUnit(with:.milli, molarMass:HKUnitMolarMassBloodGlucose)creates the exact unit for blood glucose in mmol/L (HealthKit uses molar mass to distinguish glucose from other substances measured in moles).doubleValue(for:)converts the quantity into a human-readable double value using the unit we specified.
This approach is far more robust than parsing the debug string, and it's exactly what HealthKit is designed for. If you want to use mg/dL instead, you can create that unit with HKUnit.milligramUnit(with: .deciliter) and use it in doubleValue(for:).
内容的提问来源于stack exchange,提问作者cLx

