I am wondering if the following is really the best way to know when a video is ready to play: Currently what I do is if currentMedia.playerQueue?.status.rawValue == 1 {
I play, else
(video has not loaded yet) I will show loading icon and then do the following to observe for when the video is ready to play:
I create a AVPlayer using the same video url and then when its ready I will call the playCurentMedia() method to play vid.
currentMedia.avPlayer = AVPlayer(url: currentMedia.videoURL!)
currentMedia.avPlayer!.addObserver(self, forKeyPath: "status", options: [.new, .initial], context: &P2SheetViewController.playerStatusContext)
Does this stragtegy ahve any flaws? Or is it a good solution?
How can I then observe for a change so I can show the video when it's ready?
Currently, I am only able to set up a AVPlayer alongside the queue so that I can observe for its change...
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("observe KVO")
// Only handle observations for the playerItemContext
guard context == &P2SheetViewController.playerStatusContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
if keyPath == #keyPath(AVPlayer.status) {
let status: AVPlayer.Status
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayer.Status(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
//Switch over status value
switch status {
case .readyToPlay:
print("READY TO PLAY")
GlobalSharedData.shared.videoAllSetToGoMedia1 = true
if GlobalSharedData.shared.p2Media1VideoWasNotReadyWhenPressedView {
baseVC.playVideoControlForP2()
}
break
// Player item is ready to play.
case .failed:
print(".UKNOWN")
break
// Player item failed. See error.
case .unknown:
print(".UKNOWN")
break
// Player item is not yet ready.
}
}
}