Swift中的AVPlayer观察者 - 已收到消息但未处理

时间:2015-07-22 18:18:42

标签: ios swift

我试图在纯Swift中为AVPlayer实现一个观察者。

我收到了错误消息:"消息已收到但未处理"。是因为我使用的观察者的构造函数中的object参数是nil吗?

我已将我的示例代码放在下面:

    player.addObserver(self, forKeyPath: "status", options:NSKeyValueObservingOptions(), context: nil)
    player.addObserver(self, forKeyPath: "playbackBufferEmpty", options:NSKeyValueObservingOptions(), context: nil)
    player.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options:NSKeyValueObservingOptions(), context: nil)
    player.addObserver(self, 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 observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "status" {
            print("Change at keyPath = \(keyPath) for \(object)")
        }

        if keyPath == "playbackBufferEmpty" {
            print("playbackBufferEmpty - Change at keyPath = \(keyPath) for \(object)")
        }

        if keyPath == "playbackLikelyToKeepUp" {
            print("Change at keyPath = \(keyPath) for \(object)")
        }
}

2 个答案:

答案 0 :(得分:17)

通常,当注册的观察者解除分配并且之后触发KVO事件时会发生此问题。为了修复,您需要在取消分配对象之前删除所有观察者。

在您的情况下,您注册了4个KVO更改并仅删除了3.以下KVO观察者未在任何地方删除,这导致了问题。

player.addObserver(self, forKeyPath: "loadedTimeRanges", options: NSKeyValueObservingOptions(), context: nil)

更改您的deallocObservers:方法,如:

private func deallocObservers(player: AVPlayer) {
    player.removeObserver(self, forKeyPath: "status")
    player.removeObserver(self, forKeyPath: "playbackBufferEmpty")
    player.removeObserver(self, forKeyPath: "playbackLikelyToKeepUp")
    player.removeObserver(self, forKeyPath: "loadedTimeRanges")
}

答案 1 :(得分:4)

我在更换方法后解决了这个问题。

    override func addObserver(_ observer: NSObject, forKeyPath keyPath: String, options: NSKeyValueObservingOptions = [], context: UnsafeMutableRawPointer?) {}

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {}