我希望这是可能的。我已在我的应用中的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();"];
}
我能够提醒元素播放器,它确实找到了嵌入的HTML对象,所以我知道javascript正在运行,但我无法让它开始播放。我已经尝试了 player.playVideo(); 和 player.play(); 但没有运气。
有什么建议吗?
答案 0 :(得分: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];
}