如何快速从 webView 获取 URL [英] How can I get the URL from webView in swift
问题描述
我有疑问,如何从 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
的加载,你可以在 UIWebviewDelegate
的 webViewDidFinishLoad
方法中获取该 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屋!