1

I have an implementation using KVO on player.status much like the suggestion documented here.

Here's the relevant bits:

var player: AVPlayer?
var url = URL(string: "some video url")!

override func viewDidLoad() {
    super.viewDidLoad()

    initializeVideoPlayer()
}

func initializeVideoPlayer() {
    let playerItem = AVPlayerItem(url: url)
    self.player = AVPlayer(playerItem: playerItem)
    let playerLayer = AVPlayerLayer(player: player)

    playerLayer.frame = self.view.layer.bounds
    videoView.layer.addSublayer(playerLayer)

    player?.addObserver(self, forKeyPath: "status", options: .new, context: nil)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "status" {
        if player?.status == .readyToPlay {
            print(player?.currentItem?.duration)
            print(CMTimeGetSeconds((player?.currentItem?.duration)!))

//          let videoLength = CMTimeGetSeconds((player?.currentItem?.duration)!)
//          videoProgressSlider.maximumValue = Float(videoLength)
        }
    }
}

Despite the status, what's returned is still NaN.

Solution:

So it's come to my attention that both AVPlayer AND AVPlayerItem have status properties. By KVO'ing the AVPlayerItem.status property as opposed to the AVPlayer.status like I had done, the duration will be returned properly.

Community
  • 1
  • 1
Sam L.
  • 43
  • 1
  • 8
  • Provide your solution as an answer, not as part of the question. You can even accept your own answer in 48 hours. – matt Apr 14 '17 at 04:36
  • However, just because the payerItem is ready doesn't mean the duration is. You may want to do KVO on the duration property. – mahboudz Dec 19 '17 at 19:40

1 Answers1

2

So it's come to his attention that both AVPlayer AND AVPlayerItem have status properties. By KVO'ing the AVPlayerItem.status property as opposed to the AVPlayer.status like I had done, the duration will be returned properly.

Jonny
  • 15,955
  • 18
  • 111
  • 232