Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVPlayerViewController stops after returning from full screen

I have an AVPlayerViewController which I initialize with an AVPlayer and some AVPlayerItem (iOS 10, Xcode 8, Objective C). The AVPlayerViewController is presented "inline" inside some subview, and everything works perfectly with the native playback controls.

When I press the native fullscreen button, it also works ok and switches to full screen mode (with Done button on top left).

My problem is when I press the Done button to return from full screen, the player for some reason stops playing, resets itself, and if I check .currentItem, I see it's nil.

What's happening here? Why can't AVPlayerViewController maintain its AVPlayerItem in between switching from/to full screen?

like image 951
mllm Avatar asked Dec 25 '16 20:12

mllm


2 Answers

Since it looks like the current behavior of AVPlayerViewController is to pause when exiting full screen, we can call play() when exiting by implementing the delegate:

class VideoView {

    private var playerViewController: AVPlayerViewController?

    func something() {

        playerViewController = AVPlayerViewController()

        // Other setups

        playerViewController?.delegate = self
    }
}

extension VideoView: AVPlayerViewControllerDelegate {

    func playerViewController(_ playerViewController: AVPlayerViewController, willEndFullScreenPresentationWithAnimationCoordinator coordinator: UIViewControllerTransitionCoordinator) {

        // The system pauses when returning from full screen, we need to 'resume' manually.
        coordinator.animate(alongsideTransition: nil) { transitionContext in
            self.playerViewController?.player.play()
        }
    }
}
like image 189
bauerMusic Avatar answered Sep 23 '22 12:09

bauerMusic


Following on from the above answer https://stackoverflow.com/a/58818395/196555 and the comment AVPlayerViewController stops after returning from full screen

I found using this extension works if you want to know if the AVPlayerViewController is playing or not

extension AVPlayer {
    var isPlaying: Bool {
        rate != 0 && error == nil
    }
}

 @objc func playerViewController(_ playerViewController: AVPlayerViewController, willEndFullScreenPresentationWithAnimationCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        let isPlaying = self.playerViewController.player?.isPlaying ?? false
        // The system pauses when returning from full screen, we need to 'resume' manually.
        coordinator.animate(alongsideTransition: nil) { _ in
            if isPlaying {
                self.playerViewController.player?.play()
            }
        }
    }
like image 26
daihovey Avatar answered Sep 25 '22 12:09

daihovey