Capture redirect url in wkwebview in ios

Prabu Raj picture Prabu Raj · Aug 10, 2017 · Viewed 28.8k times · Source

How do I capture the redirection url in when using WKWebView like if a webpage redirects to another page on submitting the username and password or some other data. I need to capture the redirected url. Is there any method in WKNavigationDelegate to override?

Answer

Reinier Melian picture Reinier Melian · Aug 10, 2017

Use this WKNavigationDelegate method

public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {
        if(navigationAction.navigationType == .other) {
            if navigationAction.request.url != nil {
                //do what you need with url
                //self.delegate?.openURL(url: navigationAction.request.url!)
            }
            decisionHandler(.cancel)
            return
        }
        decisionHandler(.allow)
    }

Hope this helps