Reputation: 4803
I want to have oxygen saturation in 2 digit decimal number. But I am getting it after dividing by 100. It means query returns HKQuantity
, but I need double value in percentage. I am not able to explain exactly. Let's look at code snippet what I have tried :
public func getOxygenLevel(completion: @escaping (Double?, Error?) -> Void) {
guard let oxygenQuantityType = HKQuantityType.quantityType(forIdentifier: .oxygenSaturation) else {
fatalError("*** Unable to get oxygen saturation on this device ***")
}
HKHealthStore().requestAuthorization(toShare: nil, read: [oxygenQuantityType]) { (success, error) in
guard error == nil, success == true else {
completion(nil, error)
return
}
let predicate = HKQuery.predicateForSamples(withStart: Date.distantPast, end: Date(), options: .strictEndDate)
let query = HKStatisticsQuery(quantityType: oxygenQuantityType,
quantitySamplePredicate: predicate,
options: .mostRecent) { query, result, error in
DispatchQueue.main.async {
if let err = error {
completion(nil, err)
} else {
guard let level = result, let sum = level.mostRecentQuantity() else {
completion(nil, error)
return
}
print("Quantity : ", sum) // It prints 97 % and I need 97 only
let measureUnit0 = HKUnit(from: "%")
let count0 = sum.doubleValue(for: measureUnit0)
print("Count 0 : ", count0) // It pronts 0.97 and I need 97 only
let measureUnit1 = HKUnit.count().unitMultiplied(by: HKUnit.percent())
let count1 = sum.doubleValue(for: measureUnit1)
print("Count 1 : ", count1) // It pronts 0.97 and I need 97 only
let measureUnit2 = HKUnit.percent()
let count2 = sum.doubleValue(for: measureUnit2)
print("Count 2 : ", count2) // It pronts 0.97 and I need 97 only
let measureUnit3 = HKUnit.count()
let count3 = sum.doubleValue(for: measureUnit3)
print("Count 3 : ", count3) // It pronts 0.97 and I need 97 only
completion(count0 * 100.0, nil)
}
}
}
HKHealthStore().execute(query)
}
}
Upvotes: 2
Views: 1055
Reputation: 3867
The documentation says Percent measures a value between 0.0 and 1.0
- so expect to multiply that by 100
Upvotes: 2