Search code examples
iosobjective-cavplayeravplayerviewcontrolleravkit

How do I dismiss the AVPlayer automatically when playback has completed?


I have an app that plays local videos using the AVPlayerViewController. But when the video has finished playing I want it to close automatically (like the MPMoviePlayerViewController used to do).

After posting this question, I managed to solve this partially thanks to the answers below and partially from Apples "Guides and Sample code".

This is the code that worked for me:

#import "ViewController.h"
@import AVFoundation;
@import AVKit;


@interface ViewController ()

@property(nonatomic, readonly) AVPlayerItem *currentItem;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)playerItemDidReachEnd:(NSNotification *) notification {
    //remove the player
   [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)playVideo:(id)sender {

    // grab a local URL to our video
    NSURL *videoURL = [[NSBundle mainBundle]URLForResource:@"bagare" withExtension:@"mp4"];

    // create an AVPlayer
    AVPlayer *player = [AVPlayer playerWithURL:videoURL];

    // create a player view controller
    AVPlayerViewController *controller = [[AVPlayerViewController alloc]init];
    controller.player = player;
    [player play];
    [self presentViewController:controller animated:YES completion:nil];

    // show the view controller
      controller.view.frame = self.view.frame;

    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(playerItemDidReachEnd:)
    name:AVPlayerItemDidPlayToEndTimeNotification
    object:_currentItem];

  }

@end

Solution

  • This should work:

    [[NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(videoDidFinish:) 
        name:AVPlayerItemDidPlayToEndTimeNotification
        object:[controller.player currentItem]];
    
    - (void)videoDidFinish:(id)notification
    {
        AVPlayerItem *p = [notification object];
        //do something with player if you want
    
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    
        //fade out / remove subview
    }