检查 UIWebView 中的链接是否按下 [英] Check if link pressed in UIWebView

查看:47
本文介绍了检查 UIWebView 中的链接是否按下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UIWebView,它的 URL 设置如下:

I have a UIWebView which is set the URL like this:

let url = NSURL (string: "http://google.com");
    let requestObj = NSURLRequest(URL: url!);
    webView.loadRequest(requestObj);

但是我希望能够检查用户是否按下了链接.

However I'd like to be able to check if the user as pressed a link.

我尝试了这样的简单操作:

I tried something simple like this:

if (url != "http://google.com") {
            println("Do Stuff");
        }

效果很好,但是这只在 viewDidLoad 中检查它,我现在每次按下链接或 URL 更改时都会检查它.

which worked fine, however this only checks it in the viewDidLoad I'd like to now every time a link is pressed or when the URL changes.

推荐答案

可以通过自定义函数查看网址

You can check the URL with making an custom function

func validateUrl (stringURL : NSString) -> Bool {

    var urlRegEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
    let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[urlRegEx])
    var urlTest = NSPredicate.predicateWithSubstitutionVariables(predicate)

    return predicate.evaluateWithObject(stringURL)
}

它将返回真或假.那是布尔

It will return true or false. That is Bool

例如:

if (validateUrl("http://google.com")) {
    //will return true
    println("Do Stuff");
}
else
{
    //If it is false then do stuff here.
}

func webView(WebViewNews: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
    if (validateUrl(request.URL().absoluteString())) {
        //if will return true
        println("Do Stuff");
    }
}

来源:https://stackoverflow.com/a/24207852/3202193

这篇关于检查 UIWebView 中的链接是否按下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆