You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift读取Apple Health血糖数据:如何仅输出7.8 mmol数值?

How to extract only the blood glucose value (e.g., 7.8 mmol) from HKQuantitySample in Apple Health?

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:

  • HKQuantitySample has a quantity property 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 22:22:42