【问题标题】:iOS - play embedded YouTube video using JavascriptiOS - 使用 Javascript 播放嵌入的 YouTube 视频
【发布时间】:2012-03-24 04:27:18
【问题描述】:

我希望这是可能的。我在我的应用程序中的 UIWebView 中嵌入了一个 YouTube 视频。我正在使用stringByEvaluatingJavaScriptFromString 方法来使用javascript。我想在应用程序中按下一个按钮,让 YouTube 视频开始播放。这是一些代码来概述我想说的。

嵌入功能:

- (void)embedVideo:(NSString *)urlString frame:(CGRect)frame {
    NSString *embedHTML = @"\
    <html><head>\
    <style type=\"text/css\">\
    body {\
    background-color: transparent;\
    color: white;\
    }\
    </style>\
    </head><body style=\"margin:0\">\
    <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
    width=\"330\" height=\"200\"></embed>\
    </body></html>";

    NSString *html = [NSString stringWithFormat:embedHTML, urlString];
    videoView = [[UIWebView alloc] initWithFrame:frame];
    [videoView loadHTMLString:html baseURL:nil];
    [self.detailedView addSubview:videoView];
}

修饰内部处理程序:

-(IBAction)detailedWatchTUI:(id)sender 
{
    [videoView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
     "script.type = 'text/javascript';"  
     "script.text = \"function start() { "
     "var player = document.getElementById('yt');"
     "player.play();"
     "}\";"  
     "document.getElementsByTagName('head')[0].appendChild(script);"];  

    [videoView stringByEvaluatingJavaScriptFromString:@"start();"]; 
}

我能够提醒元素 player 并且它确实找到了嵌入的 HTML 对象,所以我知道 javascript 正在工作,但是我无法让它开始播放。我试过 player.playVideo();player.play(); 没有运气。

有什么建议吗?

【问题讨论】:

    标签: ios uiwebview youtube embed stringbyevaluatingjavascr


    【解决方案1】:

    你可以试试这个:在 UIWebView 中循环子视图,找到播放按钮并在代码中点击它:

    - (UIButton *)findButtonInView:(UIView *)view
    {
        if ([view isMemberOfClass:[UIButton class]]) {
            return (UIButton *)view;
        }
        for (UIView *subview in view.subviews) {
            UIButton *button = [self findButtonInView:subview];
            if (button) {
                return button;
            }
        }
        return nil;
    }
    - (void)playButtonTapped
    {
        UIButton *button = [self findButtonInView:self.webView];
        [button sendActionsForControlEvents:UIControlEventTouchUpInside];
    }
    

    【讨论】:

    • 此实施将不再有效。 UIWebView 不再包含 UIButton。
    猜你喜欢
    • 2013-06-14
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 2017-11-03
    相关资源
    最近更新 更多