Ios 如何在swift中从HealthKit获取血氧饱和度?
我想知道血氧饱和度是2位小数。但我在除以100后得到它。这意味着查询返回Ios 如何在swift中从HealthKit获取血氧饱和度?,ios,swift,xcode,healthkit,Ios,Swift,Xcode,Healthkit,我想知道血氧饱和度是2位小数。但我在除以100后得到它。这意味着查询返回HKQuantity,但我需要双倍的百分比值。我无法准确地解释。让我们看看我尝试过的代码片段: public func getOxygenLevel(completion: @escaping (Double?, Error?) -> Void) { guard let oxygenQuantityType = HKQuantityType.quantityType(forIdentifier: .oxyge
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衡量的是0.0到1.0之间的一个值
——所以希望乘以100是的,这就是我在上一篇文章中所做的,但如果我们能直接从HealthKit获得,我想不会。注意单位乘以(by:)-这是将单位乘以以获得一种新的单位。这与价值相乘无关。例如,米每秒,是单位长度除以单位时间得到的速度单位。“磅-英尺”(扭矩),即单位质量乘以单位长度得到力的单位。