Check if link pressed in UIWebView

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

let url = NSURL (string: "");
    let requestObj = NSURLRequest(URL: url!);

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

  • Access Container View Controller from Parent iOS
  • Easiest way to truncate float to 2 decimal places?
  • How to make custom MKPolyline in SWIFT with additional argument - color
  • Why would I use if and let together, instead of just checking if the original variable is nil? (Swift)
  • How to create Selector with parameters from string
  • Swift: Override object method
  • I tried something simple like this:

    if (url != "") {
                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.

    Solutions Collect From Internet About “Check if link pressed in UIWebView”

    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("")) {
        //will return true
        println("Do Stuff");
        //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 :