Check if link pressed in UIWebView

▼魔方 西西 提交于 2019-12-11 08:55:39

问题


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");
        }

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.


回答1:


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

for example :

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

Call this function in

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

Source : https://stackoverflow.com/a/24207852/3202193



来源:https://stackoverflow.com/questions/31347143/check-if-link-pressed-in-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!