Swift AVPlayerItem完成后关闭 [英] Swift AVPlayerItem close when finished
问题描述
我对Swift和iOS开发非常陌生,所以请原谅我的无知.
I'm extremely new to Swift and iOS development, so please forgive my ignorance.
我正在尝试在视频播放完毕后自动关闭AVPlayer.我曾考虑附加"playerDidFinishPlaying"侦听器以接收通知,但是一旦收到通知,便找不到关闭控制器的方法/事件.我希望模仿单击完成"按钮的操作.
I'm trying to have the AVPlayer close automatically when the video is done playing. I've thought to attach the "playerDidFinishPlaying" listener to receive the notification, but once I have it, I can't find the method/event to close the Controller. I'm looking to mimic the action of clicking the "Done" button.
这是一小段代码.希望这是足够的信息.如果没有,我可以提供更多信息
Here is a small snippet of code. Hopefully this is enough information. If not, I can provide further info
let destination = segue.destinationViewController as! AVPlayerViewController
let url = NSURL(string: "video url")
destination.player = AVPlayer(URL: url!)
destination.player?.play()
我添加了以下通知,但是同样,一旦获得通知,我不确定该怎么做...
I've added the following notification, but again, I'm not sure what to do with it once I have it...
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:",
name: AVPlayerItemDidPlayToEndTimeNotification,
object: destination.player!.currentItem)
func playerDidFinishPlaying(note:NSNotification){
print("finished")
// close window/controller
}
最后,我知道我需要删除观察者,但是我不确定何时何地这样做.任何帮助将不胜感激.
Lastly, I know I'll need to remove the observer, but I'm not sure when or where to do so. Any help is greatly appreciated.
推荐答案
要关闭"控制器,应调用dismissViewControllerAnimated(true, completion: nil)
In order to "close" the controller, you should call dismissViewControllerAnimated(true, completion: nil)
因此代码如下:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:",
name: AVPlayerItemDidPlayToEndTimeNotification,
object: destination.player!.currentItem)
func playerDidFinishPlaying(note:NSNotification){
print("finished")
dismissViewControllerAnimated(true, completion: nil)
}
如果您的viewController
位于UINavigationController
堆栈中,则还可以执行以下操作:
if your viewController
is inside of a UINavigationController
stack, you can also do:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:",
name: AVPlayerItemDidPlayToEndTimeNotification,
object: destination.player!.currentItem)
func playerDidFinishPlaying(note:NSNotification){
print("finished")
navigationController?.popViewControllerAnimated(true)
}
要删除观察者,您可以在deinit{}
内执行:
And for remove the observer, you can do within deinit{}
:
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
这篇关于Swift AVPlayerItem完成后关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!