youtube

Embedding YouTube Within iPhone Apps

| 8 Comments

Here is a method I recently devised for getting YouTube videos to work in a useable and clean way within iPhone Apps. It assumes a basic familiarity with Xcode 4 and Objective-C.

Embed YouTube in iPhone App

Sample Video “Cycles” by Cyriak Harris

Download Source (.zip package, 33KB)

What This Method Does

There are several offerings out there for embedding YouTube into your app, most of which are variations on the code provided by YouTube themselves, and this is no different. What is new about this approach is that it positions the thumbnail centrally in all device orientations using some tweaked CSS, places the thumbnail against a black background (which is trickier to work out than it sounds), and enables you to pass a video URL dynamically to the embed code.

The example I give launches the video in a modal view, which is useful if you are working with a Tab Bar application or Navigation Controller stack with a portrait-only orientation, but still want to have videos displayed landscape. Using a modal gets around the issue of all views in a Tab Bar application needing to adhere to the same orientation as outlined by Matt Long, or any other orientation problems. You could, of course, adapt the code to remove the use of a modal if you so wished.

The Launcher View

In this example I am using two view controller classes, one that manages a XIB with some ‘view video’ buttons, and then one for the display of the actual video.

First, create a UIViewController subclass with an associated XIB called “VideoLauncherViewController”. In the interface file, add the following:

#import <UIKit/UIKit.h>
#import "VideoViewController.h"

@interface VideoLauncherViewController : UIViewController {

    NSString *videoURL;

}

@property (nonatomic, retain) NSString *videoURL;

- (IBAction) launchVideo;

@end

Nothing too complex here, just a property to hold the URL for the video and a method declaration. Once the property has been synthesized and released, this is how the method should be implemented in VideoLauncherViewController.m:

- (IBAction) launchVideo {

self.videoURL = @"http://youtube.com/embed/-0Xa4bHcJu8";

VideoViewController *videoViewController = [[[VideoViewController alloc] initWithNibName:nil bundle:nil] retain];

videoViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
videoViewController.videoURL = self.videoURL;

[self presentModalViewController:videoViewController animated:YES];

[videoViewController release];
}

You’ll get an error about videoViewController not having a videoURL property, but this will get sorted out once it is added in the next step.

The last section of the URL string, found directly after youtube.com/embed/, can be substituted for that of any YouTube video. Just use the ‘share’ button on the YouTube page to get the relevant code:

Getting a Video URL

Passing this URL value to the next view in the way shown above means you could extend the class to make the choice of video user selected, or altered programatically, for instance.

In the XIB, make a button, and bind it to the method, as shown below (click to enlarge):

Launch Screen XIB

The Video View

Now create a second UIViewController subclass and XIB called “VideoViewController”. Here’s the interface:

#import <UIKit/UIKit.h>

@interface VideoViewController : UIViewController {

    IBOutlet UIWebView *videoView;
    NSString *videoURL;
    NSString *videoHTML;

}

@property(nonatomic, retain) IBOutlet UIWebView *videoView;
@property(nonatomic, retain) NSString *videoURL;
@property(nonatomic, retain) NSString *videoHTML;

- (void) embedYouTube;
- (IBAction) closeModal;

@end

Again, synthesize and release the properties in the implementation, then add these methods:

- (void)embedYouTube {

videoHTML = [NSString stringWithFormat:@"\
<html>\
<head>\
<style type=\"text/css\">\
iframe {position:absolute; top:50%%; margin-top:-130px;}\
body {background-color:#000; margin:0;}\
</style>\
</head>\
<body>\
<iframe width=\"100%%\" height=\"240px\" src=\"%@\" frameborder=\"0\" allowfullscreen></iframe>\
</body>\
</html>", videoURL];

[videoView loadHTMLString:videoHTML baseURL:nil];
}

- (IBAction) closeModal {
[self dismissModalViewControllerAnimated:YES];
}

Lets go through some of that.

First of all we assign a string of HTML code to the videoHTML property, which will be used to embed the video within a UIWebView. The HTML contains some inline CSS for centering the video correctly on the screen. Note that some characters in the string need to be escaped, notably double quotation marks with a backslash ‘\’ and the percent sign with an extra ‘%’. New lines also need to be preceded with a backslash.

Because this is a stringWithFormat, we can also insert dynamic values, so the %@ symbols found within the src=”" attribute are replaced by whatever value is held by the videoURL property, as sent through from the Launcher view, and identified there at the end of the message.

The next step is to add the following to the - (void)viewDidLoad method:

videoView.backgroundColor = [UIColor blackColor];
videoView.opaque = NO;

[self embedYouTube];

This code sorts out the black background mentioned earlier (trying to achieve this is Interface Builder doesn’t work), plus there is a message to run the embed method.

Finally you need to alter - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation so it is simply returning YES to allow for all orientations:

    // Return YES for supported orientations
    return YES;

VideoView XIB

Open the VideoViewController.xib, and drag a UIWebView instance from the library onto the canvas. It should scale to fill the full width and height of the canvas.

Next, download and unzip this button graphic, and add both sizes of the ‘close-dark.png’ image to your project.

Drag a Round Rect Button from the library and place it roughly in the top left corner of your main view.

In the Attributes Inspector, set the Type to ‘Custom’, and the background image for the button as ‘close-dark.png’. Also change the Title to ‘Close’, the text colour to white and the font size to 14.0.

In the Size Inspector, set the X position to 36, the Y position to 24, the width to 60 and the height to 30.

Select File’s Owner and bind the videoView outlet to the UIWebView instance and the closeModal action to the ‘Close’ button.

When you are done, it should look like the example below (click to enlarge):

Edited XIB in Interface Builder

The Result

This should work both in the simulator and an actual device.

When you build and run and tap the button on the launch screen, the modal view is presented with the static video thumbnail.

YouTube Thumbnail

Tapping the thumbnail will play the video fullscreen, which can be viewed in either landscape or portrait orientations. Pressing the blue ‘Done’ button will return the user to the thumbnail screen. Pressing the ‘Close’ button on the thumbnail screen will dismiss this modal view.

YouTube Player Portrait

YouTube Landscape

Conclusion

This method provides a clean and extensible way of embedding YouTube videos in your apps, which should work in most situations.

The source code is released under the BSD 3-Clause License.

If you have any problems with the code, or have improved it in some way, feel free to leave a comment below.

If you enjoyed this post, please consider sharing it using the above buttons, leaving a comment or subscribing to the RSS feed.

8 Comments

  1. Thank you very much!!! it’s great tutorial!!!

    • Glad you found it useful Osman. I’m not entirely satisfied with the result, so will update the post if I come up with any improvements.

  2. Hi, Great tutorial. The problem I am having is this:

    Once I open up the modal view I see the youtube image of the video but once I start playing it all I hear is the audio, no video.

    I basically just grabbed your VideoViewcontroller.h, .m and .xib files and imported them into my workspace. In my own viewcontroller class I call your VideoViewController. Any ideas?

    Your xcode project when I compile and link it runs as expected.

    If you can email me at the supplied email with any insights that would be great!

    Thanks!
    -Chris

    • Hi Chris,

      without seeing your source, if the video is playing but with only audio (and presumably works fine on YouTube), I would have to guess that the issue lies how the video is being decoded. Check that your iPhone Simulator and/or physical device is running the most recent version of iOS.

  3. How could i autorun the video without display a thumbnail ? I used the autorun param but it didn’t work.

    • Not sure there is a way, because of how iOS deals with YouTube videos. You either get to use the in-app thumbnail method as shown in this post, or you provide a http link, which opens in the iOS YouTube app, but doesn’t give you an easy way for the user to return to yours.

      If anyone knows of a solution, let me know!

  4. hi~James Brocklehurst,i’m a new iOS developer,as i wan’t to download your source on this websit,but it doesn’t work,will you please send this sourcecode to my emailbox. laofoot@gmail.com

Leave a Reply

Required fields are marked *.

*


Spam protection by WP Captcha-Free