问题
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