swiftuiwebviewswift3nsurl

How can I get the URL from webView in swift


I have question, how can I fetch the url from the webView? I perform the following code and I get the nil

Code I'm trying :

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    webView.loadRequest(URLRequest(url: URL(string: "https://www.youtube.com/watch?v=Vv2zJErQt84")!))
    if let text = webView.request?.url?.absoluteString{
         print(text)
    }
}

Solution

  • You are not getting url because webView has not finished the loading of that requested URL, you can get that URL in webViewDidFinishLoad method of UIWebviewDelegate. For that you need to set delegate of webView with your current ViewController and need to implement UIWebviewDelegate.

    webView.delegate = self
    

    Now you can get current loaded URL of webView in webViewDidFinishLoad method.

    func webViewDidFinishLoad(_ webView: UIWebView) {
        if let text = webView.request?.url?.absoluteString{
             print(text)
        }
    }