如何在swift中从webView获取URL

nc1teljy  于 2023-03-07  发布在  Swift
关注(0)|答案(4)|浏览(354)

我有一个问题,我如何从webView中获取url?我执行以下代码,并获得nil
我正在尝试的代码:

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

cclgggtu1#

由于webView尚未完成加载所请求的URL,因此无法获取url,您可以在UIWebviewDelegatewebViewDidFinishLoad方法中获取该URL。为此,您需要使用当前ViewController设置webView的委托,并需要实现UIWebviewDelegate

webView.delegate = self

现在,您可以使用webViewDidFinishLoad方法获得webView的当前加载URL

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

n7taea2i2#

对于swift 5swift 4.2,请使用let url = webView.url?.absoluteString:-
首次导入WebKit:-

import WebKit

然后添加协议:-

class ViewController: UIViewController, WKNavigationDelegate

然后添加委托人:-

//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)")
    }
}
ktca8awb

ktca8awb3#

这是一个Swift 3版本,请确保您已经在类声明中添加了UIWebViewDelegate,并在viewDidload()中设置了webView.delegate = self

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

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

rt4zxlrg4#

参考:
如果要查看正在导航以进行加载的URL,请使用此委托方法。navigationAction专门显示正在导航的页面。它可以与webview.url不同

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

相关问题