0

trying to play a video with AVPlayer like this:

if let video =  card.pageImageVideoController.controllers[0] as? VideoController{
    video.player.play()
}

I noticed that the video doesn't play. So I inspected deeper and found out that when I call the function .play() the AVPlayer current Item is nil. I thought that the solution for this should be to add KVO observer for the player to see when the item is ready to play. I used this stack overflow question. And I modified the previous code like this:

var playbackLikelyToKeepUpContext = 0

if let video = card.pageImageVideoController.controllers[0] as? VideoController{

    video.player.addObserver(self, forKeyPath: "currentItem.playbackLikelyToKeepUp",
    options: .new, context: &playbackLikelyToKeepUpContext)

}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    guard let videoController = topCard!.pageImageVideoController.controllers[0] as? VideoController else { return }
    if context == &playbackLikelyToKeepUpContext {
        if videoController.player.currentItem!.isPlaybackLikelyToKeepUp {
            // loadingIndicatorView.stopAnimating() or something else
            print("ready")
        } else {
            // loadingIndicatorView.startAnimating() or something else
            print("not ready")
        }
    }
}

But the function observeValue is never called. I don't know why.

gcharita
  • 7,729
  • 3
  • 20
  • 37
StackGU
  • 868
  • 9
  • 22

1 Answers1

0

If your idea is to check if the item is ready to play or not. Then better you put observer for status. And check error in the observer function. As mentioned in the following document: https://developer.apple.com/documentation/avfoundation/avplayeritem

Manish Punia
  • 747
  • 4
  • 9