2

当我单击 UIWebview 时,我试图在 Safari 中打开一个链接(就像广告显示一样)。以下代码正在使用,但是当我单击 webview 时,它在 UIWebview 中打开了一些链接(不是全部)。

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


    if (webView1==webview) {

        if (UIWebViewNavigationTypeLinkClicked == navigationType) {

            [[UIApplication sharedApplication] openURL:[request URL]];
            return NO;
        }

        return YES;

    }
}

这里发生的情况是,如果该 UIWebView 中有任何文本链接,那么它会正确打开,但是如果 UIWebview 带有图像,那么它会在同一个 UIWebview 而不是新浏览器中打开。

我当前的代码

     - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.

        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com/files/ad.htm"]]];
    [_webView setBackgroundColor:[UIColor clearColor]];
    [_webView setOpaque:NO];
    _webView.scrollView.bounces = NO;


    }

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

    return YES;
}

当我加载应用程序时,我可以看到广告

当我点击该广告(UIWebview)时,它会在同一个 UIWebview 而不是浏览器中打开

4

1 回答 1

0

似乎这些图像已使用锚标签链接...

尝试这个...

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

    static NSString *reguler_exp = @"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9-]*[a-zA-Z0-9])[.])+([A-Za-z]|[A-Za-z][A-Za-z0-9-]*[A-Za-z0-9])$";
//Regular expression to detect those certain tags..You can play with this regular expression based on your requirement..

    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reguler_exp];
//predicate the matched tags.

    if ([resultPredicate evaluateWithObject:request.URL.host]) {
        [[UIApplication sharedApplication] openURL:request.URL];
        return NO; 
    } else {
        return YES; 
    }
}

编辑:不要让这个委托方法第一次被调用。添加一些逻辑,它不会在第一次加载 webview 时被调用。

SOP的新要求,见下文评论

如何检测 uiwebview 上的触摸,

1)将tapgesture添加到您的webview。(在您的viewcontroller.h中添加UIGestureRecognizerDelegate之前)

例子:

UITapGestureRecognizer* singleTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTap:)];
singleTap.numberOfTouchesRequired=1;
singleTap.delegate=self;
[webview addGestureRecognizer:singleTap];

2)然后添加这个委托方法,

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    //return YES,if you want to control the action natively;
    //return NO,in case your javascript does the rest.
}

注意:如果您想检查触摸是原生的还是 htmml(javascript),请查看这里的小教程,关于处理 javascript 事件等......希望这对您有所帮助..

于 2013-08-22T08:30:58.947 回答