Reputation: 2357
I am using Apple's HealthKit & have everything correctly Authorized & Working for my own locale (USA).
However, I would like to get the user's preferred units (HKUnit setting) for "distanceWalkingRunning". In my case this is "mi" (for miles). For other world regions, it could of course be km, etc.
Apple's HealthStore offers this function:
func preferredUnits(for quantityTypes: Set<HKQuantityType>,
completion: @escaping ([HKQuantityType : HKUnit], Error?) -> Void)
When I use this function in code below:
var usrPreferredDistUnits: HKUnit?
let quantityType : Set = [HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!]
healthStore.preferredUnits(for: quantityType) { (preferredType, error) in
//self.usrPreferredDistUnits = preferredType; // error! how to extract HKUnit???
print("\(preferredType)") }
I get the following print results:
[HKQuantityTypeIdentifierDistanceWalkingRunning: mi]
This is correct for my locale ("mi" for Miles) - so my code is working as expected.
However, I cant' figure out the syntax to "extract" ONLY the HKUnit part (= mi) of the returned value pair into my variable "var preferredDistanceUnit: HKUnit?".
Can anyone help me with the correct syntax for that one line of code!?
Thanks!
Upvotes: 1
Views: 427
Reputation: 2357
OK - figured it out myself!
Correct Answer is:
self.usrPreferredDistUnits = preferredType.first?.value;
Upvotes: 4