How can I get the URL from webView in swift

て烟熏妆下的殇ゞ 提交于 2019-12-22 10:26:59

问题


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

回答1:


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



回答2:


Here's a Swift 3 version, make sure you have added UIWebViewDelegate in your class dseclaration and set webView.delegate = self in viewDidload():

func webViewDidFinishLoad(_ webView: UIWebView) {
    UIApplication.shared.isNetworkActivityIndicatorVisible = false

    let urlString = webView.request!.url!.absoluteString
    print("MY WEBVIEW URL: \(urlString)")
}



回答3:


For swift 4 and swift 4.2 use let url = webView.url?.absoluteString :-

First import WebKit :-

import WebKit

Then add protocol :-

class ViewController: UIViewController, WKNavigationDelegate

Then add delegate:-

    //MARK:- WKNavigationDelegate

func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
    print(error.localizedDescription)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    print("Strat to load")

    if let url = webView.url?.absoluteString{
        print("url = \(url)")
    }
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("finish to load")

    if let url = webView.url?.absoluteString{
        print("url = \(url)")
    }
}



回答4:


FYI:

If you want to see which url is navigating for load then use this delegate method. navigationAction specifically show which page is navigating. it can be diff than webview.url

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    super.webView(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler)
    let request = navigationAction.request
}


来源:https://stackoverflow.com/questions/40946931/how-can-i-get-the-url-from-webview-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!