[英]How to get oxygen saturation from HealthKit in swift?
我想要 2 位十進制數的氧飽和度。 但我在除以 100 后得到它。這意味着查詢返回HKQuantity
,但我需要百分比的雙倍值。 我無法准確解釋。 讓我們看看我嘗試過的代碼片段:
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)
}
}
文檔說Percent measures a value between 0.0 and 1.0
- 所以期望將它乘以 100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.