Showing YouTube Video in a iOS 6 App

Recently, I worked on an app that needed to play YouTube videos. The process proved more challenging than I thought. This article will provide a complete solution.

First, create an HTML template file in your project. This will extract out HTML from Objective-C code. We will call it YouTubeTemplate.txt.

body, div {
  margin: 0px;
  padding: 0px;
#media_area {
  width: %gpx;
  height: %gpx;
  <div id="media_area"> </div>
var ytPlayer = null;

function onYouTubePlayerAPIReady() {
  ytPlayer = new YT.Player('media_area', 
    {width: '%g', height: '%g', videoId: '%@',
      playerVars: {modestbranding: 1, rel: 0, showinfo:0},
      events: {'onReady': onPlayerReady, 'onError': onError}
function onPlayerReady(e) {;
function onError(data) {
<script src=""></script>

A few things to note here:

  • The <script> tag to include YouTube API JavaScript must appear after the <script> tag where onYouTubePlayerAPIReady() is defined. The API calls onYouTubePlayerAPIReady()┬áto get things started. If you define the function after YouTube API, in certain situations the function may not get called.
  • From onPlayerReady() method we play the video. This effectively achieves the auto play feature. The “autoplay” property in playerVers did not work for me.

Next, create a view controller class and add a UIWebView to its view.

@interface VideoPlayerController : UIViewController
@property(strong, nonatomic) IBOutlet UIWebView* webView;

Define a function in the class as shown below. You can call it from anywhere to start playing a video.

- (void) setupVideoPlayer: (NSString*) youtubeVideoId {
    [self.webView stopLoading];

    NSError *error = nil;

    //Prepare the HTML from the template
    NSString *template = [NSString stringWithContentsOfFile:
                          [[NSBundle mainBundle]
                           pathForResource:@"YouTubeTemplate" ofType:@"txt"]
    NSString *htmlStr = [NSString stringWithFormat: template,                         
        self.webView.frame.size.width, self.webView.frame.size.height,                         
        self.webView.frame.size.width, self.webView.frame.size.height,

    //Write the HTML file to disk
    NSString *tmpDir = NSTemporaryDirectory();
    NSString *tmpFile = [tmpDir
                          stringByAppendingPathComponent: @"video.html"];
    [htmlStr writeToFile: tmpFile atomically:TRUE
            encoding: NSUTF8StringEncoding error:NULL];
    //Enable autoplay
    self.webView.mediaPlaybackRequiresUserAction = NO;

    //Load the HTML
    [self.webView loadRequest:[NSURLRequest requestWithURL:
        [NSURL fileURLWithPath:tmpFile isDirectory:NO]]];
    //Autoplay doesn't work with loadHTMLString
    //[self.webView loadHTMLString:htmlStr baseURL:nil];

A couple of tricks to note here:

  • mediaPlaybackRequiresUserAction of the UIWebView must be set to NO for autoplay to work.
  • We must call loadRequest of the UIWebView to load the HTML. If we call loadHTMLString then auto play doesn’t work for some reason.

2 thoughts on “Showing YouTube Video in a iOS 6 App

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s