如何快速从 HealthKit 中获取氧饱和度?
Posted
技术标签:
【中文标题】如何快速从 HealthKit 中获取氧饱和度?【英文标题】:How to get oxygen saturation from HealthKit in swift? 【发布时间】:2021-04-22 13:16:02 【问题描述】:我想要 2 位十进制数字的氧饱和度。但我在除以 100 后得到它。这意味着查询返回HKQuantity
,但我需要百分比的双倍值。我无法准确解释。让我们看看我尝试过的代码 sn-p :
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)
【问题讨论】:
【参考方案1】:文档说Percent measures a value between 0.0 and 1.0
- 所以希望乘以 100
【讨论】:
是的,这就是我最后所做的,但期待我们是否可以直接从 HealthKit 获取 我不这么认为。小心 unitMultiplied(by:) - 这是将单位相乘以获得一种新的单位。这不是乘以值。例如每秒米,是单位长度除以单位时间得到速度单位。 “磅英尺”(扭矩),即单位质量乘以单位长度得到单位力。以上是关于如何快速从 HealthKit 中获取氧饱和度?的主要内容,如果未能解决你的问题,请参考以下文章
是否可以在 Apple Watch Series 6 上通过您自己的应用程序查询血氧饱和度传感器?
如何从 HealthKit 跑步锻炼中获取海拔增益、节奏和跑步速度?