【发布时间】:2019-10-28 18:21:31
【问题描述】:
我有以下代码通过 Swift 中的 KVO 观察白平衡变化。
self.addObserver(self, forKeyPath: "videoInput.device.deviceWhiteBalanceGains", options: [.new, .old], context: &whitebalanceGainsObserverContext)
然后在 observeValue(...) 中,我这样做:
if context == &whitebalanceGainsObserverContext {
if let newNSValue = change?[.newKey] as? NSValue {
var gains = AVCaptureDevice.WhiteBalanceGains()
newNSValue.getValue(&gains)
/* Crashes here on some devices in AppStore, throws an exception */
let newTemperatureAndTint = self.videoInput?.device.temperatureAndTintValues(for: gains)
}
}
我永远无法重现崩溃,所以我想知道如何避免崩溃。我要进行哪些检查以避免引发异常?
编辑:我还尝试使用新的观察 API,如下所示:
deviceWBGainsObservation = observe(\.videoInput?.device.deviceWhiteBalanceGains, options: [.old, .new]) { (obj, change) in
if let newNSValue = change.newValue {
}
}
甚至这个,
deviceWBGainsObservation = videoDevice?.observe(\.deviceWhiteBalanceGains, options: [.old, .new]) {[unowned self] (object, change) in
if let newNSValue = change.newValue {
}
}
还有这个:
private var videoDevice:AVCaptureDevice? {
didSet {
deviceWBGainsObservation = videoDevice?.observe(\.deviceWhiteBalanceGains, options: [.old, .new]) {[unowned self] (object, change) in
if let newNSValue = change.newValue {
}
}
}
问题是在这种情况下更改值始终为零。为什么会这样?
【问题讨论】:
-
如何从 XCode 获取完整的崩溃日志?我只看到回调。
-
我添加了回溯。
-
在与 Swift 和 AVFoundation 一起使用之前,我在 observe(_:options:changeHandler:) 中发现了很多错误。这就是我仍然使用observeValue的原因。
-
@matt 你能举例说明我如何将此调用转换为在 Swift 中正常工作的 observable(_:options:changeHandler:) 吗?
-
啊,因为设备可以在生命周期中随时更改。
标签: ios avfoundation avcapturesession avcapturedevice