Wednesday, 15 February 2012

Embed Youtube Native player in a UIWebview

No, the iPhone still doesn't do Flash, but if you haven't already noticed, the Safari browser on the iPhone is clever enough to turn any YouTube embed into a clickable thumbnail that launches the native YouTube player app on the phone. You can take advantage of this feature in your app by using a UIWebView. Here's how:

1. Set up a UIWebView in your app. You can make it part of a xib or create it programmatically. Size the UIWebView according to how large you want the clickable thumbnail to be.

2. Grab the video url using the same method as the one described above.

3. Call the loadHTMLString:baseURL: method on the UIWebView instance with some carefully constructed HTML that contains the YouTube embedded player code snippet and some supporting HTML to make sure that the video thumbnail appears correctly. Set the base URL to the URL of your website (it doesn't do anything here -- ordinarily UIWebView uses it to handle relative URL links correctly).

The best way to illustrate this is with a code snippet. Note the use of the viewport HTML meta parameter and the consistent use of width and height parameters throughout.

// webView is a UIWebView, either initialized programmatically or loaded as part of a xib.

NSString *htmlString = @"<html><head>
<meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = no, width = 212\"/></head>
<body style=\"background:#F00;margin-top:0px;margin-left:0px\">
<div><object width=\"212\" height=\"172\">
<param name=\"movie\" value=\"\"></param>
<param name=\"wmode\" value=\"transparent\"></param>
<embed src=\"\"
type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"212\" height=\"172\"></embed>

[webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:@""]];

One of the biggest benefits of this approach is that your app does not have to quit in order for the video to start playing. In fact, the iPhone will keep your app running in the background while it fires up the YouTube player to play the video. After the video finishes playing (or when the user hits "Done"), the user is automatically taken back to your app. This experience is very similar to watching embedded YouTube videos in the iPhone Safari browser and is just as seamless.

Happy coding and don't forget to list your app in the YouTube Project Gallery once it goes live in the App Store!

Note: Above method work only on an actual device, not in the iPhone simulator, since it does not have a YouTube player.
Courtesy : Youtube API Blog