Close player when video is finished in AVPlayerViewController

By pressing a button in my app it plays a local video using the AVPlayerViewController.

However when the end of the video is reached the video just stops and the player is still open.

I want the player to automatically close when the video has finished playing and return to the previous view (with the button).


This is my code:


-(IBAction)playVideo1;
{
  
    NSURL *videoURL = [[NSBundle mainBundle]URLForResource:@"video1" withExtension:@"mp4"];

    AVPlayer *player = [AVPlayer playerWithURL:videoURL];
  
    AVPlayerViewController *controller = [[AVPlayerViewController alloc]init];
    controller.player = player;
    [player play];
   
    [self addChildViewController:controller];
    [self.view addSubview:controller.view];
    controller.view.frame = self.view.frame;
}

You need to add an observer for the AVPlayerItemDidPlayToEndTimeNotification

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "donePlaying:", name: AVPlayerItemDidPlayToEndNotification, object: nil)


You can then remove the AVPlayerViewController when you are notified of this event.

func donePlaying(notification:NSNotification) {
     //Dismiss AVPlayerViewController
}

Hi,


I have encountered same problem. I have already used AVPlayerItemDidPlayToEndNotification to get notified when player completes playing. But controller notified for few video files (mp4) and reset it won't.


I have detailed this question in this thread : https://stackoverflow.com/questions/44544669/avplayer-pauses-video-when-it-seek-to-0-00

Close player when video is finished in AVPlayerViewController
 
 
Q