草庐IT

ios - UIWebview 不能很好地显示 iOS 8 的嵌入式 youtube

coder 2024-01-12 原文

我很难在 UIWebview 中播放 embed 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) 如何在点击播放按钮后立即播放视频?

谢谢。

最佳答案

创建一个普通的 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 view 的 Controller 中就像下面那样

- (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()"];
}

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

关于ios - UIWebview 不能很好地显示 iOS 8 的嵌入式 youtube,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26270450/

有关ios - UIWebview 不能很好地显示 iOS 8 的嵌入式 youtube的更多相关文章

  1. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  2. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  3. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  4. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  5. ruby-on-rails - Ruby rand() 不能接受变量? - 2

    我对此有点困惑。我在RoR项目中的最终目标是从我的数据库中获取单个随机配置文件。我想它应该是这样的:@profile=Profile.find_by_user_id(rand(User.count))它一直抛出错误,因为user_id0不存在,所以我把它的一部分拿出来检查发生了什么:@r=rand(User.count)每次都返回0。发生什么了?我注册了5个假用户和5个相关配置文件来测试这个。如果我将Profile.find_by_user_id(rand(User.count))重写为Profile.find_by_user_id(3)它工作得很好。User.count也在工作。所以

  6. ruby - 为什么我不能从 ruby​​ 中的选定键创建新的散列? - 2

    这个问题困扰了我一段时间。这不是一件困难的事情,但我不知道为什么没有简单的方法来做到这一点,我敢打赌有但我没有看到。我只想取一个散列,像这样:cars={:bob=>'Pontiac',:fred=>'Chrysler',:lisa=>'Cadillac',:mary=>'Jaguar'}然后做类似的事情cars[:bob,:lisa]得到{:bob=>'Pontiac',:lisa=>'Cadillac'}我这样做了,效果很好:classHashdefpick(*keys)Hash[select{|k,v|keys.include?(k)}]endendruby-1.8.7-p249

  7. ruby-on-rails - 为什么 Rails 可以使用 `if` 作为哈希键但在 Ruby 中不能 - 2

    在纯Rubyirb中,不能输入{if:1}。该语句不会终止,因为irb认为if不是符号,而是if语句的开始。那么为什么Rails可以有before_filter接受if作为参数?该指南的代码如下:classOrderunless也会发生同样的事情。 最佳答案 这是一个irb问题,而不是Ruby。bash=>ruby-e"puts({if:1})"bash=#{:if=>1}您可以改用pry。它将正确读取输入。https://github.com/pry/pry 关于ruby-on-rai

  8. ruby - 不能将 `each` 的所有或大多数情况替换为 `map` 吗? - 2

    Enumerable#each和Enumerable#map的区别在于返回的是接收者还是映射后的结果。回到接收者是微不足道的,你通常不需要在each之后继续一个方法链,比如each{...}.another_method(我可能没见过这样的案例。即使你想回到接收者那里,你也可以通过tap来实现)。所以我认为所有或者大部分使用Enumerable#each的情况都可以用Enumerable#map代替。我错了吗?如果我是对的,each的目的是什么?map是否比each慢?编辑:我知道当您对返回值不感兴趣时​​使用each是一种常见的做法。我对这种做法是否存在不感兴趣,但感兴趣的是,除了从

  9. ruby - 如何更改此正则表达式以从未指定 v 参数的 Youtube URL 获取 Youtube 视频 ID? - 2

    目前我正在使用这个正则表达式从YoutubeURL中提取视频ID:url.match(/v=([^&]*)/)[1]我怎样才能改变它,以便它也可以从这个没有v参数的YoutubeURL获取视频ID:http://www.youtube.com/user/SHAYTARDS#p/u/9/Xc81AajGUMU感谢阅读。编辑:我正在使用ruby​​1.8.7 最佳答案 对于Ruby1.8.7,这就可以了。url_1='http://www.youtube.com/watch?v=8WVTOUh53QY&feature=feedf'url

  10. ruby - 为什么我不能将一个 fixnum 除以另一个 fixnum? - 2

    我目前正在尝试将包含数字82,000的散列counts["email"]除以包含值130万的变量total。当我运行putscounts["email"]/total时,我得到0。为什么我不能对这些进行除法? 最佳答案 您正在执行除法,尽管不是您预期的那样。在Ruby中有许多不同的整数除法:#Integerdivision:5/4#=>1#Floatingpointdivision:5.fdiv(4)#=>1.25#Rationaldivision:5.quo(4)#=>Rational(5,4)您还可以将其中一个整数转换为Floa

随机推荐