Search code examples
iosswiftavplayer

I want to add activity indicator to my AVPlayer when it's buffering


private func startVideo() {
    if let url = URL(string: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/VolkswagenGTIReview.mp4") {
        player = AVPlayer(url: url)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        playerViewController.view.frame = avPlayerView.bounds
        addChild(playerViewController)
        avPlayerView.addSubview(playerViewController.view)
        playerViewController.didMove(toParent: self)
        player?.play()
    }
}

I need to add an activity loader whenever the video is buffering.


Solution

  • You can get this working using the following code. Observing the KeyPath on the Player can make you achieve this.

    var activityIndicator: UIActivityIndicatorView!
    override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
            if player != nil {
                player.play()
                player.addObserver(self, forKeyPath: "timeControlStatus", options: [.old, .new], context: nil)
            }
        }
    override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            if keyPath == "timeControlStatus", let change = change, let newValue = change[NSKeyValueChangeKey.newKey] as? Int, let oldValue = change[NSKeyValueChangeKey.oldKey] as? Int {
                if #available(iOS 10.0, *) {
                    let oldStatus = AVPlayer.TimeControlStatus(rawValue: oldValue)
                    let newStatus = AVPlayer.TimeControlStatus(rawValue: newValue)
                    if newStatus != oldStatus {
                       DispatchQueue.main.async {[weak self] in
                           if newStatus == .playing || newStatus == .paused {
                            self!.activityIndicator.stopAnimating()
                           } else {
                            self!.activityIndicator.startAnimating()
                           }
                       }
                    }
                } else {
                    // Fallback on earlier versions
                    self.activityIndicator.stopAnimating()
                }
            }
        }