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.
I did some correction to the code above.
Here is full solution:
The key here is to set
playsinline=1
in your iFrame player, andallowsInlineMediaPlayback = true
andmediaPlaybackRequiresUserAction = false
for yourUIWebView
. Here's my implementation in Swift:Apparently the problem was with the nil base url, when I changed it to resourceURL the autoplay worked.
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):
Use following code to play a youtube video in the
UIWebView
Here we required "embed link" :
You'll get output like -
copy the link in "src" field, this is your embed link
Now just put this embed link on the place of "YOU_TUBE LINK" in the following code: