From a table view cell, I play video from a url:
let player = AVPlayer(url: URL(string: "https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8")!)
player.automaticallyWaitsToMinimizeStalling = false
let vc = AVPlayerViewController()
vc.player = player
// Loop video
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player.currentItem, queue: .main) { [weak self] _ in
player.seek(to: CMTime.zero)
player.play()
}
self.parentViewController.present(vc, animated: true, completion: {
if #available(iOS 10.0, *) {
vc.player?.playImmediately(atRate: 1.0)
} else {
vc.player?.play()
}
})
How can I detect when the AVPlayerViewController is closed/dismissed? I want to do something when it's closed.
There is no specific delegate or notification that I know of for when the AVPlayerViewController is dismissed.
However, you could try the following steps since you present the AVPlayerViewController
1. Conformance to the UIViewControllerTransitioningDelegate
Make the UIViewController that presents the AVPlayerViewController conform to the transitioning delegate
class YourVC: UIViewController, UIViewControllerTransitioningDelegate
2. AVPlayerController SetUp
Make the view controller presenting the AVPlayerController the transitioningDelegate of the AVPlayerController
let vc = AVPlayerViewController()
// Add this
vc.transitioningDelegate = self
vc.player = player
3. Finally, implement the transition delegate function
// MARK: UIViewControllerTransitioningDelegate
// Gets called when a modal was dismissed
func animationController(forDismissed dismissed: UIViewController)
-> UIViewControllerAnimatedTransitioning?
{
// The dismissal was before the movie ended
print("AVPlayerController dismissed")
return nil
}
Give this a go and see if this helps
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