Friday, February 4, 2011

How To Play YouTube Videos Within an Application




Your Ad Here


Playing a video (of a supported file format) on the iPhone is very easy using the MPMoviePlayerController class. You just create an instance of the class and initialize it with the URL of the video. The controller plays the video in full screen mode and returns back to your application when it’s done.
However, if the URL of the video is recognized by the iPhone as a YouTube URL then the Apple URL Scheme mechanism kicks in and launches the YouTube app. In this scenario control will not return to your app after the video has played. (The behavior is equivalent of calling [UIApplication openURL:] with the video URL.)
One workaround is to use a UIWebView and load it with the video URL. The drawback with this approach is that the user will see the rather ugly YouTube mobile web site and has to find and tap on the link of the video to play it.

YouTube Mobile

Another, visually more appealing, option is to create a small UIWebView on your screen and load it with the YouTube embed code. The result is a small button like image that shows the YouTube play button above a screen image from the video. When the user taps the image, the iPhone video player opens in full screen mode as usual, and when the video is done control is returned back to this screen.

YouTube Video Embedded in iPhone App

Here’s the code:


  1. - (void)embedYouTube:(NSString*)url frame:(CGRect)frame {  
  2.  NSString* embedHTML = @"\ 
  3.     \ 
  4.  \ 
  5.  body {\ 
  6.  background-color: transparent;\ 
  7.  color: white;\ 
  8.  }\ 
  9.  \ 
  10.  \ 
  11.      
  12.  width=\"%0.0f\" height=\"%0.0f\">\ 
  13.     ";  
  14.  NSString* html = [NSString stringWithFormat:embedHTML, url, frame.size.width, frame.size.height];  
  15.  if(videoView == nil) {  
  16.    videoView = [[UIWebView alloc] initWithFrame:frame];  
  17.    [self.view addSubview:videoView];  
  18.  }  
  19.  [videoView loadHTMLString:html baseURL:nil];  
  20. }

 
Submit Express Inc.Search Engine Optimization Services