I want to be able to format and print speed in localised form. I found a few pods that can do that but I'm looking for embedded solution (if possible).
Currently I do next:
let unit = HKUnit.meterUnit(with: .kilo).unitDivided(by: .hour())
let output = HKQuantity(unit: unit, doubleValue: 12.5).description
But in this case I cannot tune anything like use h
instead of hr
.
As said @Allan we have to use MeasurementFormatter
. Check out the ready to use solution below.
import UIKit
import HealthKit
let value = NSMeasurement(doubleValue: 12.5, unit: UnitSpeed.milesPerHour)
let formatter = MeasurementFormatter()
formatter.numberFormatter.maximumFractionDigits = 2
formatter.string(from: value as Measurement<Unit>) // prints 12.5 mph
The description
method of HKQuantity
does not return a localized value and it is meant for debugging, not for display. Convert the HKQuantity
instance to an NSMeasurement
and use NSMeasurementFormatter
(documentation here) to localize the value for display.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With