Capture redirect url in wkwebview in ios

后端 未结 5 1335
孤独总比滥情好
孤独总比滥情好 2020-12-09 02:09

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 t

5条回答
  •  余生分开走
    2020-12-09 02:26

    For me, using decidePolicyFor navigation delegate's method didn't work.

    It didn't work because WKNavigationDelegate's method

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
    

    will only be called when there is a full-page reload. To be able to catch all WKWebView's request URL changes, a Key-Value observer will have to be placed on the WKWebView's URL property.

    First, in viewDidLoad add:

    webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
    

    Second, add observeValue method

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            if keyPath == #keyPath(WKWebView.url) {
                // Whenever URL changes, it can be accessed via WKWebView instance
                let url = webView.url
            }
        }
    

提交回复
热议问题