Jak automatycznie odtwarzać wideo YouTube w UIWebView

Widziałem wiele postów na ten temat, ale nadal nie mogłem znaleźć idealnej odpowiedzi na ten problem.

Więc mam widok tabeli, a każda komórka ma przycisk odtwarzania wewnątrz niego. Gdy użytkownik dotknie przycisku Odtwórz, dodaję UIWebView do tej komórki i odtwarzam film na YouTube.

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];
}

Problem:

Ten kod nie odtwarza filmu tak, jak chcę, po prostu uruchamia odtwarzacz YouTube i pokazuje go za pomocą czerwonego przycisku odtwarzania YouTube. Tylko wtedy, gdy użytkownik dotknij czerwonego przycisku, wideo rozpocznie odtwarzanie.
Tak więc użytkownik musi stuknąć dwa przyciski, aż rozpocznie się film-nie jest to najlepsze doświadczenie użytkownika...

Jak już mówiłem, widziałem wiele postów na ten temat, niektóre w ogóle nie działają, a niektóre działają, ale z pewnymi problemami, które mnie denerwują.

Jednym z działających rozwiązań znalazłem w ten post by @ilias, pokazuje jak to zrobić pracy z ładowaniem HTML z pliku (zamiast ciągu jak ja), problem z tym approche jest że do każdego odtwarzanego filmiku muszę:
Załaduj plik htm - > umieść w nim ID wideo - > Zapisz plik na dysk - > dopiero teraz mogę odtworzyć wideo.

Dziwne jest to, że to rozwiązanie działa tylko podczas ładowania żądania widoku sieci Web z pliku, jeśli próbuję załadować żądanie z łańcucha równego zawartości pliku, to nie działa.

Author: Community, 2013-03-30

5 answers

Najwyraźniej problem był z bazowym adresem URL zerowym, kiedy zmieniłem go na resourceURL autoplay działał.

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

Pełny kod do autoplay filmów z youtube (znowu ten kod głównie oparty na ten post właśnie zmieniłem go na wczytanie z łańcucha zamiast pliku):

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]];
}
 48
Author: Eyal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:27

Kluczem jest ustawienie playsinline=1 w Twoim odtwarzaczu iFrame oraz allowsInlineMediaPlayback = true i mediaPlaybackRequiresUserAction = false dla twojego UIWebView. Oto moja implementacja w 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)
 10
Author: JAL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-25 21:22:54

Oto pełne rozwiązanie:

//
//  S6ViewController.m
//  
//
//  Created by Ökkeş Emin BALÇİÇEK on 11/30/13.
//  Copyright (c) 2013 Ökkeş Emin BALÇİÇEK. All rights reserved.
//

#import "S6ViewController.h"

@interface S6ViewController ()

@end

@implementation S6ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self playVideoWithId:@"sLVGweQU7rQ"];

}




- (void)playVideoWithId:(NSString *)videoId {

     NSString *youTubeVideoHTML = @"<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:'768', height:'1024', videoId:'sLVGweQU7rQ', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";

    NSString *html = [NSString stringWithFormat:youTubeVideoHTML, videoId];

    UIWebView *videoView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
    videoView.backgroundColor = [UIColor clearColor];
    videoView.opaque = NO;
    //videoView.delegate = self;
    [self.view addSubview:videoView];

    videoView.mediaPlaybackRequiresUserAction = NO;

    [videoView loadHTMLString:youTubeVideoHTML baseURL:[[NSBundle mainBundle] resourceURL]];
}

@end
 7
Author: okkesemin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-30 18:29:46
- (void)playVideoWithId:(NSString *)videoId {

NSString *youTubeVideoHTML = @"<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:'768', height:'1024', videoId:'%@', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";

NSString *html = [NSString stringWithFormat:youTubeVideoHTML, videoId];

UIWebView *videoView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];
videoView.backgroundColor = [UIColor clearColor];
videoView.opaque = NO;
//videoView.delegate = self;
[self.view addSubview:videoView];

videoView.mediaPlaybackRequiresUserAction = NO;

[videoView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
}

Dokonałem korekty powyższego kodu.

 4
Author: Vannian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-13 05:44:28

Użyj poniższego kodu, aby odtworzyć film na youtube w UIWebView

Tutaj wymagane jest "embed link":

  • po prostu otwórz swój link youtube w przeglądarce
  • Kliknij prawym przyciskiem myszy na wideo
  • Wybierz opcję "Get embed code"
  • Otrzymasz wyjście jak -

    <iframe width="640" height="390" src="https://www.youtube.com/embed/xtNXZA4XMBY" frameborder="0" allowfullscreen></iframe>
    
  • Skopiuj link w polu "src" , to jest Twój link do osadzenia

    Teraz po prostu umieść ten link embed na miejscu "YOU_TUBE LINK" w następującym kodzie:

    NSString *htmlString = [NSString stringWithFormat:@"<html><head><meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = yes, width = 320\"/></head><body style=\"background:#00;margin-top:0px;margin-left:0px\"><div><object width=\"320\" height=\"480\"><param name=\"movie\" value=\"YOUTUBE_LINK\"></param><param name=\"wmode\" value=\"transparent\"></param><embed src=\"YOUTUBE_LINK\"type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"320\" height=\"480\"></embed></object></div></body></html>"];
    
    [self.webView_youTube loadHTMLString:htmlString baseURL:nil];
    
 2
Author: nilam_mande,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-15 07:21:40