Search code examples
iosswiftavplayerobserversios9.1

addObserver to AVPlayer never being called when AVPlayer Ready to play?


I have added the observer to AVPlayer but it's not calling the function when avplayer status is ready to play. The function called twice when video start playing but both the time duration parameter of AVPlayer return 'nan' and I need to get duration when AVPlayer ready to play.

    playerController.player = player
    self.addChildViewController(playerController)
    self.view.addSubview(playerController.view)
    playerController.view.frame = self.view.frame
    playerController.showsPlaybackControls = false
    player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions(), context: nil)
    player.play()

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if player.currentItem?.status == AVPlayerItemStatus.ReadyToPlay {
      print("a")  
    }
}

Solution

  • replace addObserver line like this:

    player.currentItem!.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions(), context: nil)