我试图在纯粹的
Swift中实现AV Player的观察者.
我收到错误:收到信息但未处理.是因为我使用的观察者的构造函数中的对象参数是否为零?
我把我的示例代码放在下面
谢谢
player.addObserver(self,forKeyPath: "status",options:NSKeyValueObservingOptions(),context: nil) player.addObserver(self,forKeyPath: "playbackBufferEmpty",forKeyPath: "playbackLikelyToKeepUp",forKeyPath: "loadedTimeRanges",options: NSKeyValueObservingOptions(),context: nil) private func deallocObservers(player: AVPlayer) { player.removeObserver(self,forKeyPath: "status") player.removeObserver(self,forKeyPath: "playbackBufferEmpty") player.removeObserver(self,forKeyPath: "playbackLikelyToKeepUp") } //observer for av play override func observeValueForKeyPath(keyPath: String,ofObject object: AnyObject,change: [NSObject : AnyObject],context: UnsafeMutablePointer<Void>) { if keyPath == "status" { println("Change at keyPath = \(keyPath) for \(object)") } if keyPath == "playbackBufferEmpty" { showAlert("No internet connection!",message: "Mixmatic requires an internet connection to continue streaming.") println("Change at keyPath = \(keyPath) for \(object)") } if keyPath == "playbackLikelyToKeepUp" { println("Change at keyPath = \(keyPath) for \(object)") } }
解决方法
通常,当注册的观察者解除分配并且之后触发KVO事件时,会发生此问题.为了修复你需要删除所有的观察者,在你的对象将被释放之前.
在您的情况下,您注册了4个KVO更改并仅删除了3个.以下KVO观察器在任何地方都不会被删除,并导致问题.
player.addObserver(self,context: nil)
更改您的deallocObservers:方法如下:
private func deallocObservers(player: AVPlayer) { player.removeObserver(self,forKeyPath: "playbackLikelyToKeepUp") player.removeObserver(self,forKeyPath: "loadedTimeRanges") }