Welcome to my iphone development code blog

Welcome to my iphone development code blog

Friday, June 4, 2010

Display YouTube Videos Without Exiting Your Application

if you’d like to play a YouTube video inside your application there are two common ways to do this, by launching the YouTube player and by using a UIWebview.
Launch Native YouTube Application

This approach will exit your application and begin the YouTube player on the iPhone:

[[UIApplication sharedApplication]
openURL:[NSURL URLWithString:@"http://www.youtube.com/watch?v=gczw0WRmHQU"]];

Clickable Thumbnail and UIWebview

If you’ve noticed in Safari on the iPhone, when the browser finds a YouTube video reference, a clickable link is created, which will start the movie when tapped without leaving Safari.

We can use the same approach within an iPhone application using a UIWebView, including a clickable link with a poster frame from the movie.

For this example I have created a separate class that subclasses UIWebView:

@interface YouTubeView : UIWebView

- (YouTubeView *)initWithStringAsURL:(NSString *)urlString frame:(CGRect)frame;


Here’s the implementation of the class:

#import "YouTubeView.h"

@implementation YouTubeView

#pragma mark -
#pragma mark Initialization

- (YouTubeView *)initWithStringAsURL:(NSString *)urlString frame:(CGRect)frame;
if (self = [super init])
// Create webview with requested frame size
self = [[UIWebView alloc] initWithFrame:frame];

// HTML to embed YouTube video
NSString *youTubeVideoHTML = @"<html><head>\
<body style=\"margin:0\">\

<embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \

width=\"%0.0f\" height=\"%0.0f\"></embed>\


// Populate HTML with the URL and requested frame size
NSString *html = [NSString stringWithFormat:youTubeVideoHTML, urlString, frame.size.width, frame.size.height];

// Load the html into the webview
[self loadHTMLString:html baseURL:nil];
return self;

#pragma mark -
#pragma mark Cleanup

- (void)dealloc
[super dealloc];


The magic here is the HTML for embedding the video content, and notice how the HTML is populated with the video URL and the desired frame size.

We can now insert this view inside a ViewController class as shown here:

// Create view that will act as link to youtube video,
// centering the view
YouTubeView *youTubeView = [[YouTubeView alloc]
frame:CGRectMake(100, 170, 120, 120)];

[[self view] addSubview:youTubeView];

Here is how the clickable link looks, the image on the left is before the poster frame has downloaded, the right includes the poster frame:

Tapping the link will start the movie in a webview.

1 comment:

  1. I have a problem on iPad devices, in iPhone when user taps on the Youtube (In UIWebView) the video starts playing in the Player which is perfect , but when i run the same code on iPad it does not open the player instead the video plays in the webview itself. Anyone knows how to get around this ?