Search code examples
iosswiftavplayeravplayeritem

Swift AVPlayerItem close when finished


I'm extremely new to Swift and iOS development, so please forgive my ignorance.

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.


Solution

  • In order to "close" the controller, you should call dismissViewControllerAnimated(true, completion: nil)

    So the code will look like:

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", 
        name: AVPlayerItemDidPlayToEndTimeNotification, 
        object: destination.player!.currentItem)
    
    func playerDidFinishPlaying(note:NSNotification){
        print("finished")
        dismissViewControllerAnimated(true, completion: nil)
    }
    

    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)
    }
    

    And for remove the observer, you can do within deinit{}:

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }