检测 AVPlayerViewController 何时关闭

use*_*425 4 ios avplayer swift avplayerviewcontroller

从表视图单元格中,我播放来自 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()
            }
        })
Run Code Online (Sandbox Code Playgroud)

如何检测何时AVPlayerViewController关闭/解除?我想在关门的时候做点什么。

Sha*_*ank 8

当 AVPlayerViewController 被解雇时,没有具体的delegate或据我所知。notification

但是,您可以尝试以下步骤,因为您提出了AVPlayerViewController

1. 符合UIViewControllerTransitioningDelegate

使AVPlayerViewControllerUIViewController符合转换委托presents

class YourVC: UIViewController, UIViewControllerTransitioningDelegate
Run Code Online (Sandbox Code Playgroud)

2.AVPlayerController 设置

使视图控制器呈现AVPlayerControllertransitioningDelegateAVPlayerController

let vc = AVPlayerViewController()

// Add this
vc.transitioningDelegate = self

vc.player = player
Run Code Online (Sandbox Code Playgroud)

3.最后实现transition delegate函数

// 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
}
Run Code Online (Sandbox Code Playgroud)

尝试一下,看看是否有帮助