I want to detect if my AVPlayer is buffering for the current location, so that I can show a loader or something. But I can't seem to find anything in the documentation for AVPlayer.
You can observe the values of your player.currentItem
:
playerItem.addObserver(self, forKeyPath: "playbackBufferEmpty", options: .New, context: nil) playerItem.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .New, context: nil) playerItem.addObserver(self, forKeyPath: "playbackBufferFull", options: .New, context: nil)
then
override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if object is AVPlayerItem { switch keyPath { case "playbackBufferEmpty": // Show loader case "playbackLikelyToKeepUp": // Hide loader case "playbackBufferFull": // Hide loader } } }
The accepted answer didn't work for me, I used the code below to show the loader efficiently.
Swift 3
//properties var observer:Any! var player:AVPlayer! self.observer = self.player.addPeriodicTimeObserver(forInterval: CMTimeMake(1, 600), queue: DispatchQueue.main) { [weak self] time in if self?.player.currentItem?.status == AVPlayerItemStatus.readyToPlay { if let isPlaybackLikelyToKeepUp = self?.player.currentItem?.isPlaybackLikelyToKeepUp { //do what ever you want with isPlaybackLikelyToKeepUp value, for example, show or hide a activity indicator. } } }
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