Play YouTube video using UIWebView on iPhone

P

Hi,

Sometimes it gets very difficult to find a way to do simple things. Playing videos on iPhone is a simple thing, using UIWebView. Just need to embed the URL to HTML tags, and then load the HTML in UIWebView.

Here is the code to do so.

Pass you URL of YouTube Video in “urlStr”.

//In .h file
UIWebView *videoView;
// In .m file

videoView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 385)];

[self embedYouTube :urlStr  frame:CGRectMake(0, 0, 320, 385)];

[self.view addSubview:videoView];

// methos to embed URL in HTML & load it to UIWebView

– (void)embedYouTube:(NSString*)url frame:(CGRect)frame

{

NSString* embedHTML = @”

<html><head>

<style type=”text/css”>

body {

background-color: transparent;

color: white;

}

</style>

</head><body style=”margin:0″>

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

width=”%0.0f” height=”%0.0f”></embed>

</body></html>”;

 

NSString* html = [NSString stringWithFormat:embedHTML, url, frame.size.width, frame.size.height];

if(videoView == nil) {

videoView = [[UIWebView alloc] initWithFrame:frame];

[self.view addSubview:videoView];

}

[videoView loadHTMLString:html baseURL:nil];

}

**Note : The UIWebView for YouTube video doesn’t load when you run it on Simulator, work on device perfectly.

 

About the author

surjit.joshi
By surjit.joshi

Category