28

I've embedded a video from YouTube via a snippet I've found on the Internet, here is the code that I've used:

    @interface FirstViewController (Private)
- (void)embedYouTube:(NSString *)urlString frame:(CGRect)frame;
@end


@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self embedYouTube:@"http://www.youtube.com/watch?v=l3Iwh5hqbyE" frame:CGRectMake(20, 20, 100, 100)];
}


- (void)embedYouTube:(NSString *)urlString 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, urlString, frame.size.width, frame.size.height];
    UIWebView *videoView = [[UIWebView alloc] initWithFrame:frame];
    [videoView loadHTMLString:html baseURL:nil];
    [self.view addSubview:videoView];
    [videoView release];
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

@end

It compiles correctly and when I open it, I see a white box positioned incorrectly, which the code created. I have two questions regarding it:

  1. How do I know if the video will play, it is just a plain white box, does the simulator play videos from YouTube?

  2. How can I position this box?

JAL
  • 41,701
  • 23
  • 172
  • 300
ayve
  • 333
  • 2
  • 7
  • 6

6 Answers6

13

Just tested your code, it works fine on an iPhone, Youtube videos are not supported on the iOS simulator though, so you'll need a real device for testing.

How can I position this box?

You are already passing the X (20), Y(20), width(100) and height(100) of the box at this line:

[self embedYouTube:@"http://..." frame:CGRectMake(20, 20, 100, 100)];

To change the position of the view afterwards, you modify its center property:

videoView.center = CGPointMake(200, 100 );
Julio Gorgé
  • 10,056
  • 2
  • 45
  • 60
  • Just a side note to this, if you do this in a modal view, when the video finishes, my app behaves strangely, it closes the modal view and UIButtons are unresponsive. Once I pulled it out of the modal view it worked fine. – steve Apr 14 '12 at 02:52
  • Hello i had same problem and now i succeed to play video in device but there is another problem that video is only played in ios version 5.1.1 , if i want to play video in below ios version 5.1.1 what should i do? – Birju Sep 18 '12 at 07:32
  • Hi I am using above code for playing video. It works perfectly for playing videos but when i pause the video came back to application then it crashes. Giving EXC_BAD_ACESS. Any idea about this. – The iCoder Sep 30 '13 at 06:04
7

Here is the sample code, its working fine on iOS 5 and later, this is the new implementation which Youtube API provided, myWeb is a UIWebView here. showinfo=0 in URL will remove the top header in the videoView.

NSString *html = [NSString stringWithFormat:@"<html><body><iframe class=\"youtube-player\" type=\"text/html\" width=\"%f\" height=\"%f\" src=\"http://www.youtube.com/embed/q1091sWVCMI?HD=1;rel=0;showinfo=0\" allowfullscreen frameborder=\"0\" rel=nofollow></iframe></body></html>",frame.size.width,frame.size.height];
[myWeb loadHTMLString:html baseURL:nil];

Hope this helps you :)

Nikesh K
  • 621
  • 6
  • 10
5

Here's a version that works in iOS 6 and with the new YouTube embed code:

- (void)embedYouTube:(NSString *)urlString frame:(CGRect)frame {
    NSString *html = [NSString stringWithFormat:@"<html><head><style type='text/css'>body {background-color: transparent;color: white;}</style></head><body style='margin:0'><iframe width='%f' height='%f' src='%@' frameborder='0' allowfullscreen></iframe></body></html>", frame.size.width, frame.size.height, urlString];
    UIWebView *videoView = [[UIWebView alloc] initWithFrame:frame];
    [videoView loadHTMLString:html baseURL:nil];
    [self.view addSubview:videoView];
}
adriandz
  • 999
  • 1
  • 10
  • 21
  • can you autoplay the movie after loading it to the webview? – João Nunes Mar 27 '13 at 12:20
  • I'm not using this code any more so I'm not sure. Have you tried it? I wouldn't be surprised if it did not autoplay. I'm just loading an external mp4 video now and it works great. – adriandz Mar 28 '13 at 01:03
0

Swift Implementation:

let webView = UIWebView(frame: self.view.frame) // Position your player frame here

self.view.addSubview(webView)
self.view.bringSubviewToFront(webView)

// Playback options: play in-line and start playing immediately
webView.allowsInlineMediaPlayback = true
webView.mediaPlaybackRequiresUserAction = false

// Set the id of the video you want to play
let videoID = "zN-GGeNPQEg" // https://www.youtube.com/watch?v=zN-GGeNPQEg

// Set up your player
let embededHTML = "<html><body style='margin:0px;padding:0px;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>function onYouTubeIframeAPIReady(){ytplayer=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}function onPlayerReady(a){a.target.playVideo();}</script><iframe id='playerId' type='text/html' width='\(self.view.frame.size.width)' height='\(self.view.frame.size.height)' src='http://www.youtube.com/embed/\(videoID)?enablejsapi=1&rel=0&playsinline=1&autoplay=1' frameborder='0'></body></html>"

// Load the HTML into your UIWebView
webView.loadHTMLString(embededHTML, baseURL: NSBundle.mainBundle().bundleURL)

Alternatively, YouTube provides a great helper class for devs to set up YouTube playback in their iOS which sets up the UIWebView for you.

JAL
  • 41,701
  • 23
  • 172
  • 300
0

swift 4

func embedYouTube(_ urlString: String, frame: CGRect) {

    let html = "<html><head><style type='text/css'>body {background-color: transparent;color: white;}</style></head><body style='margin:0'><iframe width='\(frame.size.width)' height='\(frame.size.height)' src='\(urlString)' frameborder='0' allowfullscreen></iframe></body></html>"
    let videoView = UIWebView(frame: frame)
    videoView.loadHTMLString(html, baseURL: nil)
    view.addSubview(videoView)
}
Quiet Islet
  • 536
  • 1
  • 8
  • 28
0

For those using Monotouch and C#, you can add this class to your project and use it to view your videos:

public class YouTubeViewer : UIWebView
{
    public YouTubeViewer(string url, RectangleF frame)
    {
        string youTubeVideoHTML = @"<object width=""{1}"" height=""{2}""><param name=""movie""
                            value=""{0}""></param><embed
                            src=""{0}"" type=""application/x-shockwave-flash"" 
                            width=""{1}"" height=""{2}""</embed></object>"; 

        string html = string.Format(youTubeVideoHTML, url, frame.Size.Width, frame.Size.Height);
        this.LoadHtmlString(html, null);
        this.Frame = frame;
    }
}

Make sure the URL you pass it, is the URL from the embed code provided from Youtube when you click the Share button. (And check the check-box for the old code)

TChadwick
  • 868
  • 10
  • 19
  • The question was for iOS – NSCoder Feb 08 '15 at 09:33
  • 2
    @NSCoder, this answer is for iOS, Monotouch is a software provided by a company called Xamarin that allows development of native iOS applications in C# instead of the now-deprecated objective-c. (Swift) – TChadwick Feb 10 '15 at 18:43