How to play video files in your iOS App

The easiest way to play video files in iOS is to use the MPMoviePlayerViewController class. This will bring up a view controller with playback controls – no hassle required. All we need is to link and import the Media Player framework.

Here’s how to do it:

@import MediaPlayer;

- (IBAction)playbackButton:(id)sender {
    
    // pick a video from the documents directory
    NSURL *video = [self grabFileURL:@"video.mov"];
    
    // create a movie player view controller
    MPMoviePlayerViewController * controller = [[MPMoviePlayerViewController alloc]initWithContentURL:video];
    [controller.moviePlayer prepareToPlay];
    [controller.moviePlayer play];
    
    // and present it
    [self presentMoviePlayerViewControllerAnimated:controller];
    
}

The controller is instantiated with a URL to the video file, and has a movie player property which we can use just like the standalone MPMoviePlayer. To play the video, we need to call both prepareToPlay and play methods, and of course present the controller – for which there’s a special method built-in to each view controller would you believe it.

The above example will automatically play the video in a new modal view, and will be automatically dismissed when the video ends. Instead of a delegate protocol, the controller uses notifications you can subscribe to for error handling, completions and interruptions (not shown here).

Note that the MPMediaPlayer, MPMoviePlayerController and MPMoviePlayerViewController are all related, but they’re not the same – despite their very similar sounding titles.

I’ve created a quick and dirty Demo Project on GitHub to demonstrate how it works.





Leave a Reply