Javascript – Youtube video autoplay on iPhone’s Safari or UIWebView

iphonejavascriptuiwebview

Is it possible to get a youtube video to autoplay on Safari and/or UIWebView? I've seen this done in an iPhone app, the tableview displays cells that do not have Youtube preview icon (pretty sure it's a UIWebView Though), when you tap the cell it directly goes to video.

Could this be done by faking a tap on the youtube video? If so, how? Would getElementById().click work?

Best Answer

the trick is to find the button in the webview. Use the following snippet.

- (void)loadWebUIViewWithYoutubeLink {
    webView.delegate = self;
    NSString *htmlString = [NSString stringWithFormat:[NSString
                             stringWithContentsOfFile:[[NSBundle mainBundle]
        pathForResource:@"YouTubeTemplate" ofType:@"txt"]],
                             @"b85hn8rJvgw",  @"b85hn8rJvgw", nil];
    [webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:@"http://youtube.com"]];
}

- (UIButton *)findButtonInView:(UIView *)view {
    UIButton *button = nil;

    if ([view isMemberOfClass:[UIButton class]]) {
        return (UIButton *)view;
    }

    if (view.subviews && [view.subviews count] > 0) {
        for (UIView *subview in view.subviews) {
            button = [self findButtonInView:subview];
            if (button) return button;
        }
    }

    return button;
}

- (void)webViewDidFinishLoad:(UIWebView *)_webView {
    UIButton *b = [self findButtonInView:_webView];
    [b sendActionsForControlEvents:UIControlEventTouchUpInside];
}
Related Topic