我是HealthKit框架的新手,希望实时获得血氧饱和度。
参考:https://github.com/coolioxlr/watchOS-2-heartrate
从这个仓库我试图查询氧饱和度
func createOxygenSaturationStreamingQuery(_ workoutStartDate: Date) -> HKQuery? {
guard let quantityType = HKObjectType.quantityType(forIdentifier: .oxygenSaturation) else { return nil }
let datePredicate = HKQuery.predicateForSamples(withStart: workoutStartDate, end: nil, options: .strictEndDate )
let predicate = NSCompoundPredicate(andPredicateWithSubpredicates:[datePredicate])
let oxygenSaturationQuery = HKAnchoredObjectQuery(type: quantityType,
predicate: predicate,
anchor: nil,
limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in
self.updateOxygenSaturation(sampleObjects)
}
oxygenSaturationQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in
self.updateOxygenSaturation(samples)
}
return oxygenSaturationQuery
}
func updateOxygenSaturation(_ samples: [HKSample]?) {
guard let oxygenSaturationSamples = samples as? [HKQuantitySample] else {return}
DispatchQueue.main.async {
// RETURN FROM HERE AS EMPTY ARRAY
guard let sample = oxygenSaturationSamples.first else { return }
let value = sample.quantity.doubleValue(for: HKUnit(from: "%/min"))
let stringValue = String(UInt16(value))
self.label.setText(stringValue)
// retrieve source from sample
let name = sample.sourceRevision.source.name
print("sample.sourceRevision.source.name : \(name)")
print("PERCENT : \(stringValue)")
}
}
附注:我正在模拟器中进行检查
我从该存储库中获得了“心率”,但是却没有氧气水平吗?
让我知道我做错了什么以及如何纠正?
最佳答案
watchOS不会自动记录氧饱和度样本,因此,除非您拥有一个可以记录此类样本并使用应用将其写入HealthKit的设备,否则您不应期望得到任何结果。