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.