Swift AVPlayerItem完成后closures
我对Swift和iOS开发非常陌生,所以请原谅我的无知。
我试图在播放完video后自动closuresAVPlayer。 我想附加“playerDidFinishPlaying”侦听器来接收通知,但一旦我有了它,我找不到方法/事件closures控制器。 我正在寻找模仿点击“完成”button的动作。
这是一小段代码。 希望这是足够的信息。 如果没有,我可以提供进一步的信息
let destination = segue.destinationViewController as! AVPlayerViewController let url = NSURL(string: "video url") destination.player = AVPlayer(URL: url!) destination.player?.play()
我已经添加了以下通知,但是一旦拥有了,我不知道该如何处理它…
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: destination.player!.currentItem) func playerDidFinishPlaying(note:NSNotification){ print("finished") // close window/controller }
最后,我知道我需要删除观察者,但我不确定何时何地这样做。 任何帮助是极大的赞赏。
为了“closures”控制器,你应该调用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
栈内,你也可以这样做:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: destination.player!.currentItem) func playerDidFinishPlaying(note:NSNotification){ print("finished") navigationController?.popViewControllerAnimated(true) }
而且为了移除观察者,你可以在deinit{}
做:
deinit { NSNotificationCenter.defaultCenter().removeObserver(self) }
SWIFT 3的更新:
注意:您正在播放audio的viewController需要:AVAudioPlayerDelegate
你也不需要观察者
class myViewController: UIViewController, AVAudioPlayerDelegate { var audioplayer = AVAudioPlayer() override func viewDidAppear(_ animated: Bool) { if soundsON{ let myFilePathString = Bundle.main.path(forResource: "backgroundSound", ofType: "mp3") if let myFilePathString = myFilePathString { let myFilePathURL = URL(fileURLWithPath: myFilePathString) do{ try audioplayer = AVAudioPlayer(contentsOf: myFilePathURL) audioplayer.delegate = self audioplayer.prepareToPlay() audioplayer.play() }catch{ print("error playing coin sound") } } } }
在这个例子中,声音将在viewDidAppear播放,当它完成时,它会调用:audioPlayerDidFinishPlaying:
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { //Check if the sound that finishes comes from a certain AVAudioPlayer if player == audioplayer{ print("The sound from -audioplayer- has finished") // If you need to dismiss the VC: dismiss(animated: true, completion: nil) } }