4

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?

  • Is there really nothing being printed? The console may be hidden, press Command + Shift + Y and click the box on the bottom-right – aheze Oct 13 '20 at 01:32
  • @aheze Unfortunately nothing is being printed for why it is crashing, all my other print statements run and when I put a break on the specific line player?.addObserver, it breaks there with an error but nothing printing for it in the console just on the right hand side of that line of code like other build errors appear. Which is why I’m confused on why nothing is printing in the console or why it is even throwing an error like that. – allenhinson214 Oct 13 '20 at 02:45

1 Answers1

3

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
gcharita
  • 7,729
  • 3
  • 20
  • 37