UIWebView - 在safari中强制导航

时间:2017-04-11 12:15:24

标签: ios objective-c uiwebview

我在objective-c中有一个UIWebView,用于加载带有嵌入视频的外部HTML(我无法访问此HTML)。此视频包含来自Google广告的前贴片广告(但未来可能来自其他提供商)。 此广告有一个指向用户可以点击的外部网站的链接,但它似乎是由javascript事件(不是常规锚点)触发的。

我已设置代理,以强制在Web视图中点击的链接在Safari中打开,但广告中的这些链接会在网页视图中保持打开状态。我认为这是因为它们是由javascript触发的。

这是我的代表:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:
(NSURLRequest *)request navigationType:
(UIWebViewNavigationType)navigationType
{
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }
return YES;
}

有没有人知道如何强制在Webview中加载的域外的任何导航在Safari中打开?我猜这种方式可以解决这个问题。

感谢。

1 个答案:

答案 0 :(得分:0)

假设你知道"内部"域提前,您可以强制所有外部域在Safari中打开:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    if (![request.url.absoluteString containsString:@"https://www.yourinternaldomain.com"]) {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }

    return YES;
}

<强>更新

根据您的评论,如果上述内容不够,您可以添加UITapGestureRecognizer来检测用户输入:

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
tapGesture.numberOfTouchesRequired = 1;
tapGesture.numberOfTapsRequired = 1;
tapGesture.delegate = self;
[self.webView addGestureRecognizer:tapGesture];

实施委托方法以确保识别您的点按:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

-tapGesture:方法中,您可以设置临时BOOL

-(void)tapGesture:(UITapGestureRecognizer *)tapGesture {
    self.userDidTap = YES;
}

然后在随后的-webView:shouldStartLoadWithRequest:navigationType:方法中,您可以检查self.userDidTap值并采取相应措施:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    if (self.userDidTap) {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }

    return YES;
}