I've been given a warning by YouTube that the embedded video in my app has a title that is meant to be clickable and take the user to YouTube.
However I cannot understand how that is meant to happen because all we're doing is using a WKWebview to load a url
Is there something I'm missing? Is there something that needs to be added to the url?
WKWebView *webView = [[WKWebView alloc] initWithFrame: self.videoContainerView.bounds];
webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"https://www.youtube.com/embed/%@", rowViewModel.videoId]]];
webView.clipsToBounds = YES;
webView.contentMode = UIViewContentModeScaleAspectFill;
[webView loadRequest:request];
I've tried looking around to see if there are parameters that can be passed but I'm not sure I found anything useful.
Turns out that YouTube blocks the navigation interaction when the user taps the title. Therefore the WebKit navigation delegate receives no calls.
But this is ONLY the case with the title.
Tapping at other places will still take you to YouTube app.
In other words:
YouTube is purposefully blocking the taps on the title and saying we are the one's violating their terms and conditions.
Therefore you need to write a hack using the WKUIDelegate
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
if (navigationAction.request.URL) {
[[UIApplication sharedApplication] openURL:navigationAction.request.URL options:@{} completionHandler:nil];
}
return nil;
}
and also inject JavaScript:
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSString *js = @"document.querySelector('.ytp-title-link').onclick = function() { "
" window.webkit.messageHandlers.openInSafari.postMessage(this.href); "
" return false; "
"};";
[webView evaluateJavaScript:js completionHandler:nil];
}
and add a script handler:
[webView.configuration.userContentController addScriptMessageHandler:self name:@"openInSafari"];
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"openInSafari"]) {
NSString *urlString = (NSString *)message.body;
NSURL *url = [NSURL URLWithString:urlString];
if (url) {
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
}
}
}