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)")
}
}
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With