如何快速从 webView 获取 URL [英] How can I get the URL from webView in swift

查看:98
本文介绍了如何快速从 webView 获取 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有疑问,如何从 webView 获取 url?我执行以下代码并得到 nil

I have question, how can I fetch the url from the webView? I perform the following code and I get the 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)
    }
}

推荐答案

你没有得到 url 因为 webView 还没有完成那个请求的 URL 的加载,你可以在 UIWebviewDelegatewebViewDidFinishLoad 方法中获取该 URL.为此,您需要使用当前的 ViewController 设置 webView 的委托,并需要实现 UIWebviewDelegate.

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

现在您可以在webViewDidFinishLoad 方法中获取webView 的当前加载的URL.

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

这篇关于如何快速从 webView 获取 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆