Phil Hudson
Phil Hudson

Reputation: 3901

AVPlayer observer in Swift - message was received but not handled

I'm trying to implement an observer for AVPlayer in pure Swift.

I'm getting the error: "message was received but not handled". Is it because the object argument in the constructor of the observer I'm using is nil?

I've placed my example code below:

    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)")
        }
}

Upvotes: 17

Views: 15894

Answers (2)

Abdul Hameed
Abdul Hameed

Reputation: 61

I solved the problem after replacing the method.

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

To

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

Upvotes: 5

Midhun MP
Midhun MP

Reputation: 107231

Normally this issue happens when the registered observer deallocates and a KVO event triggers after that. For fixing you need to remove all observers before your object is going to be deallocated.

In your case, you registered for 4 KVO changes and removing only 3. The following KVO observer is not removed anywhere and it is causing the issue.

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

Change your deallocObservers: method like:

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")
}

Upvotes: 17

Related Questions