I have an AVPlayer which loads its content from a remote url. When the AVPlayer is created it shows a thumbnail of the video. I cant seem to find any information for a notification or a property i can listen to to see when this thumbnail is added as I want to show a loading screen before the thumbnail is added and remove it after.
class VideoView: UIView {
private var playerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
public var videoURL: URL? {
didSet {
guard videoURL != oldValue
else { return }
if let videoURL = videoURL {
avPlayer = AVPlayer(url: videoURL)
playerLayer.player = avPlayer
}
}
}
private var avPlayer: AVPlayer?
override public static var layerClass: AnyClass {
return AVPlayerLayer.self
}
}
I have tried observing when the player's currentItem.status value is readyToPlay however the thumbnail is added after the status changes to readyToPlay
observer = currentItem.observe(\.status) { [weak self] (currentItem, change) in
if currentItem.status == .readyToPlay {
self?.overlay?.isHidden = false
}
}
Thanks
AVPlayerLayer has a property that you can observe: readyForDisplay. Its a BOOL and the documentation reads:
A Boolean value that indicates whether the first video frame has been made ready for display for the current item of the associated player. Use this property as an indicator of when best to show or animate-in a player layer into view. A player layer may be displayed, or made visible, while this property is NO, however the layer will not have any user-visible content until the value becomes YES. This property remains NO for a player’s currentItem whose asset contains no enabled video tracks. This property is key value observable using Key-value observing.
You should be able to observe this property and remove the loading spinner when the first frame of the video gets loaded. Note that this property remains NO for a player item that doesn't contain any video tracks. Hope this helps.
Here is the code to listen for when a thumbnail has been added to an AVVideoPlayerViewController (meaning that it is ready for display)
observer = avVideoPlayerViewController.observe(\.isReadyForDisplay) { [weak self] (avVideoPlayerViewController, change) in
if avVideoPlayerViewController.isReadyForDisplay {
print("Video player is ready for display")
} else {
print("Video player is not ready for display")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With