【问题标题】:UIWebview does not display embedded youtube well for iOS 8UIWebview 不能很好地显示 iOS 8 的嵌入式 youtube
【发布时间】:2014-12-03 21:55:03
【问题描述】:

我很难在 UIWebview 中播放嵌入 youtube。

如果我使用 youtube 的默认嵌入格式,它不会在 UIWebview 中显示任何内容。只是空白。

NSString *htmlString = @"<html><body><iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/XNnaxGFO18o?rel=0\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
[self.webView loadHTMLString:htmlString baseURL:nil];

我搜索了一下,发现以下代码有效。

NSString* embedHTML = @"\
<html><body style=\"margin:0;\">\
<<div class=\"emvideo emvideo-video emvideo-youtube\"><embed id=\"yt\" src=\"http://www.youtube.com/embed/bPM8LKYMcXs?hd=1\" width=\"320\" height=\"250\"></embed></div>\
</body></html>";
[self.webView loadHTMLString:embedHTML baseURL:nil];

但是,有一个问题。如果我点击播放按钮,它没有任何反应。我必须点击播放按钮几次并等待一段时间,然后它开始旋转然后播放。

所以我有两个问题。

1) 你有更好的方法在 UIWebView 中播放嵌入的 youtube 视频吗? 2) 如何在点击播放按钮后立即播放视频?

谢谢。

【问题讨论】:

    标签: ios uiwebview youtube ios8


    【解决方案1】:

    创建一个普通的 html 文件并将其命名为 youtubeEmbedding.html 并将其添加到 youtubeEmbedding.html 中的项目中,只需将以下代码添加到 .html 文件中

    <!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);
            firstScriptTag.requestFullScreen();
            var ytplayer = null;
    
            function onYouTubePlayerAPIReady() 
            {
                ytplayer = new YT.Player(
                                         'player',
                                         {
                                         videoId:'%@',
                                         width:'%0.0f',
                                         height:'%0.0f', %@
                                         playerVars:
                                         {
                                         'controls': %d,
                                         'playsinline' : 0,
                                         'rel':0,
                                         'showinfo':0
                                         },
                                         });
            }
    
    
        function onPlayerReady(event)
        {
            event.target.playVideo();
        }
    
        function stopVideo()
        {
            if (ytplayer)
            {
                ytplayer.stopVideo();
                ytplayer.clearVideo();
            }
            return 'STOPPED';
        }
    
        function playVideo()
        {
            if (ytplayer)
            {
                ytplayer.playVideo();
            }
            return 'PLAY';
        }
    
        function pauseVideo()
        {
            if (ytplayer)
            {
                ytplayer.pauseVideo();
                ytplayer.clearVideo();
            }
            return 'PAUSED';
        }
    
        function getPlayerState()
        {
            return ytplayer.getPlayerState();
        }
    
        function isPlaying()
        {
            return (myPlayerState == YT.PlayerState.PLAYING);
        }
        function isPaused()
        {
            return (myPlayerState == YT.PlayerState.PAUSED);
        }
        function onPlayerError(event)
        {
            alert("Error");
        }
        </script>
    </body>
    

    在你使用 web 视图的控制器中,如下所示

    - (void)viewDidLoad
    {
       BOOL autoPlay = NO;
       // Do any additional setup after loading the view, typically from a nib.
       NSString *youTubeVideoHTML  = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"youtubeEmbedding" ofType:@"html"] encoding:NSUTF8StringEncoding error:nil];
       NSString *autoPlayString    =  autoPlay ? @"events: {'onReady' : onPlayerReady }," : @""; //customise it weather u want to autoplay or not
       NSURL *url = [NSURL URLWithString:@"https://www.youtube.com/watch?v=AYo72E7ZMHM"];
       NSString *lastComponent = [url query];
       NSString *videoId   = [lastComponent  stringByReplacingOccurrencesOfString:@"v=" withString:@""]; //get  the video id from url
       NSInteger controls  = 1; //i want to show controles for play,pause,fullscreen ... etc
       NSString *html      = [NSString stringWithFormat:youTubeVideoHTML, videoId, CGRectGetWidth(_webView.frame), CGRectGetHeight(_webView.frame), autoPlayString, controls]; //setting the youtube video width and height to fill entire the web view 
      _webView.mediaPlaybackRequiresUserAction = NO;
      _webView.delegate = self; //not needed
      [_webView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]]; //load it to webview
    
    }
    
    
    //for playing action 
    - (IBAction)playAction:(id)sender 
    {
      [_webView stringByEvaluatingJavaScriptFromString:@"ytplayer.playVideo()"];
    }
    

    如果您有任何问题,请发表评论,希望这对您有所帮助.. :)

    【讨论】:

    • 奇怪,uiwebview 是空白的。我打印出 html,内容正确。
    • @user890207 在新项目中测试
    • 是的。它很奇怪。从昨天开始,即使是我的旧代码也运行良好。谷歌似乎做了一些改变。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 2012-08-29
    • 2015-01-08
    • 2011-06-22
    • 2019-11-10
    • 1970-01-01
    • 2012-01-20
    相关资源
    最近更新 更多