I am trying to add an observer to my AVPlayer in swift that allows reads when the video begins playing to control other functions on my player. When I run the following code:
func setUpPlayer() {
if let url = URL(string: urlString) {
player = AVPlayer(url: url)
let playerLayer = AVPlayerLayer(player: player)
self.layer.addSublayer(playerLayer)
playerLayer.frame = self.frame
player?.play()
player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "currentItem.loadedTimeRanges" {
print(change)
}
}
My app crashes with no explanation in the console. I have found the line of code that is causing it which is:
player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)
But I am not sure why it is crashing. Any ideas on what could be causing this?
You can try using the new method of KVO since swift 4.
To observe
loadedTimeRanges
property of theplayer
'scurrentItem
you can simply do this:Keep the returned
observation
reference as long as you want to observe the property. To manually stop observing, just setobservation
reference tonil
: