Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autoplay a YouTube video in a UIWebView

I have seen a lot of posts in here about this issue, but still couldn't find a perfect answer for this problem.

So I have a tableview, and each cell has a play button inside it. When the user tap the play button, I add a UIWebView to this cell, and play a YouTube video.

static NSString *youTubeVideoHTML = @"<html>\     <body style=\"margin:0;\">\         <iframe class=\"youtube-player\" type=\"text/html\" width=\"%0.0f\" height=\"%0.0f\" src=\"http://www.youtube.com/embed/%@\" frameborder=\"0\">\         </iframe>\     </body>\     </html>";   - (void)playVideoWithId:(NSString *)videoId {     NSString *html = [NSString stringWithFormat:youTubeVideoHTML, self.frame.size.width, self.frame.size.height, videoId];      [self loadHTMLString:html baseURL:nil]; } 

The problem:

This code doesn't actually play the video like I want, it just initiate the YouTube player and show it with the YouTube red play button. Only when user tap the red button, the video will start playing.
So user has to tap two buttons until the video starts - not the best user experience...

Like I said I saw many posts about this issue, some not work at all, and some works but with some issues that bugs me.

One of the working solutions I found was in this post by @ilias, he shows how to get this working with loading the HTML from a file (instead of a string like I do), problem with this approche is that for every video I play I need to:
load the htm file -> embed the video Id in it -> write the file to disc -> only now I can play the video.

Strange thing is that this solution only work when you load the web view request from a file, if I try to load the request from a string equal to the file content, that doesn't work.

like image 855
Eyal Avatar asked Mar 30 '13 10:03

Eyal


People also ask

How do you put youtube on autoplay?

Go to the watch screen of any video. At the bottom of the video player, click the Autoplay switch to set it to On or Off .

How do I autoplay an iframe video?

Allowing iframes to autoplay video content You should also note the need to use the allowfullscreen attribute in complement to the allow attribute in order to support browsers that do not support allow attribute. If you are using amp-iframe and autoplay you need to add allow="autoplay" to your amp-iframe element.


2 Answers

Apparently the problem was with the nil base url, when I changed it to resourceURL the autoplay worked.

[self loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];   

The full code for autoplay youtube videos (again this code mostly based on this post I just changed it to load from a string instead of a file):

static NSString *youTubeVideoHTML = @"<!DOCTYPE html><html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"http://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'%0.0f', height:'%0.0f', videoId:'%@', events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";    - (void)playVideoWithId:(NSString *)videoId {     NSString *html = [NSString stringWithFormat:youTubeVideoHTML, self.frame.size.width, self.frame.size.height, videoId];      [self loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]]; } 
like image 92
Eyal Avatar answered Sep 23 '22 13:09

Eyal


The key here is to set playsinline=1 in your iFrame player, and allowsInlineMediaPlayback = true and mediaPlaybackRequiresUserAction = false for your UIWebView. Here's my implementation in Swift:

// Set up your UIWebView let webView = UIWebView(frame: self.view.frame) // or pass in your own custom frame rect  self.view.addSubview(webView) self.view.bringSubviewToFront(webView)  // Set properties webView.allowsInlineMediaPlayback = true webView.mediaPlaybackRequiresUserAction = false  // get the ID of the video you want to play let videoID = "zN-GGeNPQEg" // https://www.youtube.com/watch?v=zN-GGeNPQEg  // Set up your HTML.  The key URL parameters here are playsinline=1 and autoplay=1 // Replace the height and width of the player here to match your UIWebView's  frame rect 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 your webView with the HTML we just set up webView.loadHTMLString(embededHTML, baseURL: NSBundle.mainBundle().bundleURL) 
like image 21
JAL Avatar answered Sep 23 '22 13:09

JAL