当视频从所有屏幕完成时自动关闭 AVPlayer
Posted
技术标签:
【中文标题】当视频从所有屏幕完成时自动关闭 AVPlayer【英文标题】:Automatically dismiss AVPlayer when video completes from ALL SCREENS 【发布时间】:2018-12-26 06:32:29 【问题描述】:当我的视频完成后,我希望它拉下 AVPlayer 并返回到主视图控制器。
我还想在连接时从我的外部屏幕/显示器下拉视频。
我该怎么做?
我在这里尝试了几个不同的答案,但到目前为止都没有奏效。
注意:四是我视频的名称
@IBAction func fourVideoPlayButton(_ sender: Any)
if let path = Bundle.main.path(forResource: "Four", ofType: "mp4")
let fourVideo = AVPlayer(url: URL(fileURLWithPath: path))
let fourVideoPlayer = AVPlayerViewController()
fourVideoPlayer.player = fourVideo
present(fourVideoPlayer, animated: true, completion:
fourVideo.play()
)
【问题讨论】:
How to detect when AVPlayer video ends playing?的可能重复 【参考方案1】:你需要添加观察者来检测玩家何时结束播放
NotificationCenter.default.addObserver(self, selector: Selector(("playerDidFinishPlaying:")),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: fourVideoPlayer.player.currentItem)
func playerDidFinishPlaying(note: NSNotification)
fourVideoPlayer.dismiss(animated: true, completion: nil)
希望对您有所帮助!
【讨论】:
我怎样才能从我的外部显示器/屏幕上消除它? 你是说从另一个 viewController 中解雇? 所以我将我的应用程序连接到 Apple TV 上的外部显示器。当视频完成时,它会从用户设备 (iPad) 中移除 AVPlayer+Controller,但它只会将结束帧留在电视上。 哦,那你可以试试以下fourVideoPlayer.view.removeFromSuperView() self.presentedviewController?.dismiss(animated: true, completion: nil) 它给了我“UIView”类型的错误值?没有成员“removeFromSuperView”【参考方案2】:在 Swift 4.2 中,
let fourPlayerController = AVPlayerViewController()
@IBAction func fourVideoPlayButton(_ sender: Any)
guard let path = Bundle.main.path(forResource: "Four", ofType:"mp4") else
return
let fourVideoPlayer = AVPlayer(url: URL(fileURLWithPath: path))
fourPlayerController.player = fourVideoPlayer
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: fourPlayerController.player?.currentItem)
present(fourPlayerController, animated: true)
fourVideoPlayer.play()
@objc func playerDidFinishPlaying(note: NSNotification)
fourPlayerController.dismiss(animated: true, completion: nil)
fourPlayerController.dismiss(true, completion: nil)
fourPlayerController.view.removeFromSuperview()
self.presentedViewController?. dismiss(true, completion: nil)
【讨论】:
感谢@Bappaditya,它成功了。我也在使用外接显示器,你知道为什么它也不会关闭我的外接显示器吗?它只是在完成时显示视频的结束帧。我希望它返回到我的主要外部视图。 如果你能分享一些代码sn-p,这将有助于我更好地理解流程 var secondWindow: UIWindow! var secondScreenView:UIView! @objc func setupScreen() if UIScreen.screens.count > 1 让 secondScreen = UIScreen.screens[1] secondWindow = UIWindow(frame: secondScreen.bounds) 让 viewController = UIViewController() secondWindow!.rootViewController = viewController secondWindow!. screen = secondScreen secondScreenView = UIView(frame: secondWindow!.frame) secondWindow!.addSubview(secondScreenView) secondWindow!.isHidden = false 对不起上面的混乱。如果更简单,您可以在此处查看。 codeshare.io/2EwxqK 你能弄清楚@Bappaditya 吗?以上是关于当视频从所有屏幕完成时自动关闭 AVPlayer的主要内容,如果未能解决你的问题,请参考以下文章