How can I get the URL from webView in swift

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

The code I'm trying is:

 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) } } 
+2
swift swift3 nsurl uiwebview
source share
2 answers

You do not get the URL because webView not finished loading the requested URL , you can get this URL in the webViewDidFinishLoad method of the UIWebviewDelegate . To do this, you need to install the webView delegate with the current ViewController and it needs to implement UIWebviewDelegate .

 webView.delegate = self 

Now you can get the current loaded URL from webView in webViewDidFinishLoad .

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

Here's the Swift 3 version, add the UIWebViewDelegate to the dseclaration class and set webView.delegate = self to viewDidload() :

 func webViewDidFinishLoad(_ webView: UIWebView) { UIApplication.shared.isNetworkActivityIndicatorVisible = false let urlString = webView.request!.url!.absoluteString print("MY WEBVIEW URL: \(urlString)") } 
0
source share

All Articles