0

I'm trying to check if the URL has changed in the webView. For example if I were to initially load a page like a Wordpress Sign In page, and I wanted to know when it changed and got redirected to the login page. I tried using this resource enter link description here but the answer seems to be incomplete and does not work.

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

urlTest is never called so i'm not sure the purpose of it.

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

And then to call this function

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

I added a return function at the end of my code, but the example does not include a return. I have very little experience in Webview, so any advice or help would be appreciated.

Community
  • 1
  • 1
bradford gray
  • 537
  • 2
  • 5
  • 18

1 Answers1

1

Use the webViewDidFinishLoad function of the UIWebViewDelegate to get the current URL loaded in your webview. Everytime the webview loads a URL the function webViewDidFinishLoad is called.

class YourClass: UIViewController, UIWebViewDelegate {

    let initialURL = URL(string: "https://www.google.com.pe/")
    @IBOutlet weak var webView:UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.loadRequest( URLRequest(url: initialURL) )
    }

    func webViewDidFinishLoad(_ webView: UIWebView) {
        if webView.request != URLRequest(url: initialURL!) {
            //DO YOUR STUFF HERE
        }
    }

}
jguillen
  • 180
  • 1
  • 9