Swift Apple Health blood glucose

285 Views Asked by At

I got access to Apple Health and I'm able to read the glucose data which is in the Simulator.

    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 any errors here.
            return
        }
        
        for sample in samples {
            print(sample)
        }
        

I gives me 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; }

Is there any possibility to only print out the 7.8 mmol? I didn't find anything in the documents from Apple. Thanks for the help.

2

There are 2 best solutions below

2
On BEST ANSWER

sample is a class of type HKQuantitySample. If you print(sample) then it will print the complete class data.

If you want to print only quantity then try printing as below

print(sample.quantity)
0
On

I bet you would also need to extract the double value itself out of the quantitiy. Here is a sample code

    let unit = HKUnit.gramUnit(with: .milli).unitDivided(by: HKUnit.liter())
    let value = sample.quantity.doubleValue(for: unit)

For the source and device of the value you can try this:

   let device = sample.device
   let sourceRevision = sample.sourceRevision

If you want, you can try out my CocoaPod. It is a wrapper above HealthKit framework to ease the reading/writing operations. Here is the link: https://cocoapods.org/pods/HealthKitReporter