【问题标题】:WKWebview: On click of button in app, play directly embedded Youtube VideoWKWebview:点击应用中的按钮,直接播放嵌入的Youtube视频
【发布时间】:2023-03-07 15:56:01
【问题描述】:

我的应用中的 UIImageView (headerView) 上有一个播放按钮。用户单击此按钮后,我想直接在此 UIImageView 的框架内显示嵌入的 YoutubeVideo。但是,首先我的 Youtube 视频没有自动播放,第二个尺寸太小了。我究竟做错了什么?我一直在谷歌搜索所有可能的答案并尝试了一切。还是与模拟器相关的问题?这是我通过点击播放按钮触发的代码:

NSString *videoIdentifier = @"EXaEz0mJXWY";

WKWebView *webView = [[WKWebView alloc] initWithFrame:self.headerView.bounds];
[webView.configuration setAllowsInlineMediaPlayback:YES];
[webView.configuration setMediaTypesRequiringUserActionForPlayback:WKAudiovisualMediaTypeNone];
[self.headerView addSubview:webView];

NSString* embedHTML = [NSString stringWithFormat:@"\
                       <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='%0.0f' height='%0.0f' src='http://www.youtube.com/embed/%@?enablejsapi=1&rel=0&playsinline=1&autoplay=1' frameborder='0'>\
                            </body>\
                       </html>", webView.frame.size.width, webView.frame.size.height, videoIdentifier];

//NSLog(@"Embeddedhtml: %@", embedHTML);
[webView loadHTMLString:embedHTML baseURL:[[NSBundle mainBundle] resourceURL]];

【问题讨论】:

    标签: objective-c wkwebview youtube-iframe-api


    【解决方案1】:

    我的 Youtube 视频没有自动播放

    您必须使用configuration 参数初始化WKWebView。之后更改配置无效。

    WKWebViewConfiguration* config = [[WKWebViewConfiguration alloc] init];
    [config setAllowsInlineMediaPlayback:YES];
    [config setMediaTypesRequiringUserActionForPlayback:WKAudiovisualMediaTypeNone];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.headerView.bounds configuration:config];
    
    

    尺寸太小了

    WKWebView 使用实际设备像素进行测量,并使用一些启发式方法进行默认缩放,而 UIKit 以点为单位返回宽度和高度。简单的解决方法是将viewport meta 添加到页面:

    <head>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    </head>
    

    【讨论】:

      猜你喜欢
      • 2017-02-22
      • 1970-01-01
      • 2012-07-09
      • 2014-12-01
      • 2015-06-20
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      • 2014-11-26
      相关资源
      最近更新 更多