Adding observer to AVPlayer causes a crash with no printout in console

602 Views Asked by At

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?

1

There are 1 best solutions below

0
On

You can try using the new method of KVO since swift 4.

To observe loadedTimeRanges property of the player's currentItem you can simply do this:

observation = player?.currentItem?.observe(
    \.loadedTimeRanges,
    options: .new
) { (item: AVPlayerItem, value: NSKeyValueObservedChange<[NSValue]>) in
    print("loadedTimeRanges: \(value.newValue ?? [])")
}

Keep the returned observation reference as long as you want to observe the property. To manually stop observing, just set observation reference to nil:

observation = nil