How can I get the URL from webView in swift

2019-05-22 13:00发布

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

4条回答
Luminary・发光体
2楼-- · 2019-05-22 13:15

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楼-- · 2019-05-22 13:15

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
}
查看更多
老娘就宠你
4楼-- · 2019-05-22 13:20

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)")
    }
}
查看更多
▲ chillily
5楼-- · 2019-05-22 13:22

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)
    }
}
查看更多
登录 后发表回答