2

I hope this is possible. I've embedded a YouTube video within a UIWebView in my app. I am using the stringByEvaluatingJavaScriptFromString approach for using javascript. I want to press a button in the app and make the YouTube video start playing. Here is some code to outline what I am trying to say.

embed function:

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

Touch up inside handler:

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

I am able to alert out the element player and it does find the embedded HTML object, so I know javascript is working, however I can't get it to start playing. I've tried player.playVideo(); and player.play(); with no luck.

Any suggestions?

Romes
  • 3,088
  • 5
  • 37
  • 52

1 Answers1

1

You can try this: loop up the subviews in UIWebView, find the play button and click it in code:

- (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];
}
Chengjiong
  • 1,282
  • 11
  • 17
  • 2
    This implementation will no longer work. The UIWebView does not contain a UIButton anymore. – Meroon Sep 18 '12 at 10:20