What type of HealthKit unit is used for VO2 Max measurements? - Swift 4
Asked Answered
A

1

6

I am writing an app in Swift 4 that uses Apple's HealthKit. I am trying to write to the "VO2 Max" metric, but I am not sure which unit to use. In the Health App itself, the unit is listed as "mL/(kg*min)" but I don't see anything like that in Apple's documentation here. My code looks like this. What should I put in place of the ??? on the second line?

writeHKMetric = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.vo2Max)!
writeHKQuantity = HKQuantity.init(unit: HKUnit.???, doubleValue: 1)

(As a reference, code to write to, say, Cycling Distance looks like this. Note the "HKUnit.mile()")

writeHKMetric = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceCycling)!
writeHKQuantity = HKQuantity.init(unit: HKUnit.mile(), doubleValue: 1)

When I attempt to use another metric, say count, I get this error:

2017-12-14 22:08:01.876935-0500 Stand Hours 2.0[478:76005] *** Terminating app due to uncaught exception '_HKObjectValidationFailureException', reason: 'HKQuantitySample 1 count  (2017-12-08 08:00:00 -0500 - 2017-12-08 08:00:00 -0500) requires unit of type Volume/Mass·Time. Incompatible unit: count'

But I don't know how to set my unit to "Volume/Mass*Time".

Ares answered 15/12, 2017 at 3:6 Comment(0)
W
12

Fun with units. HKUnit has methods for multiplying and dividing units.

The following code builds the desired unit.

let kgmin = HKUnit.gramUnit(with: .kilo).unitMultiplied(by: .minute())
let mL = HKUnit.literUnit(with: .milli)
let VO₂Unit = mL.unitDivided(by: kgmin)

let writeHKMetric = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.vo2Max)!
let writeHKQuantity = HKQuantity(unit: VO₂Unit, doubleValue: 1)
print(writeHKQuantity)

Output:

1 mL/min·kg

A less fun but simpler solution (thanks Allan) to create the unit is to do:

let VO₂Unit = HKUnit(from: "ml/kg*min")
Whitening answered 15/12, 2017 at 3:36 Comment(1)
You can also just instantiate the unit this way: let unit = HKUnit(from: "mL/min·kg")Davy

© 2022 - 2024 — McMap. All rights reserved.