2017-02-05 92 views
0

我想要訪問Swift 3中的UIWebView的URL。下面是我用來完成此操作的代碼(我的webview的名稱是RootView):在Swift 3中訪問UIWebView的URL

let currentURL : NSString = RootView.request?.URL?.absoluteString

但是,我得到一個錯誤,說「類型'URLRequest'的值沒有成員'URL'」,這使我無法編譯。我知道以前的堆棧溢出用戶已經成功地使用了這一行代碼,所以我不確定是什麼阻止了我也獲得URL。問題在於蘋果對Swift 3所做的改變嗎?謝謝!

這裏是我的全ViewController.swift文件,我把這個代碼:

import UIKit 

class ViewController: UIViewController, UIWebViewDelegate { 

    @IBOutlet weak var RootView: UIWebView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     self.RootView.delegate = self 
     let url1 = URL (string: "https://www.google.com")! 
     RootView.loadRequest(URLRequest(url: url1)) 
     RootView.scrollView.isScrollEnabled = true 
     RootView.isUserInteractionEnabled = true 
     let currentURL : NSString = RootView.request?.URL?.absoluteString 
     print(currentURL) 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 
} 
+0

給出更多的上下文。如周邊代碼 – ctabuyo

回答

0

你有三種選擇訪問URL

let currentURL : String? = RootView.request?.mainDocumentURL?.absoluteString 
let currentURL : String? = RootView.request?.url?.absoluteString 
let currenturl : String? = RootView.stringByEvaluatingJavaScript(from: "window.location.href") 

但所有這三個值將返回nil,因爲請求需要時間,在請求完成之前它們不會準備好。試試。

import UIKit 

class URLResearchVC: UIViewController , UIWebViewDelegate { 

    @IBOutlet weak var RootView: UIWebView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     self.RootView.delegate = self 
     let url1 = URL (string: "https://www.google.com")! 
     RootView.loadRequest(URLRequest(url: url1)) 
     RootView.scrollView.isScrollEnabled = true 
     RootView.isUserInteractionEnabled = true 
     let currentURL : String? = RootView.request?.mainDocumentURL?.absoluteString 
     let currentUrl : String? = RootView.request?.url?.absoluteString 
     let currenturl : String? = RootView.stringByEvaluatingJavaScript(from: "window.location.href") 
     print(currentURL) 
     print(currentUrl) 
     print(currenturl) 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 

    func webViewDidStartLoad(_ webView: UIWebView) { 
     print("-------") 
     print(webView.request?.mainDocumentURL) 
     print("-------") 
     print(webView.request?.url?.absoluteString) 
     print("-------") 
     print(webView.stringByEvaluatingJavaScript(from: "window.location.href")) 
    } 
    func webViewDidFinishLoad(_ webView: UIWebView) { 
     print("-------") 
     print(webView.request?.mainDocumentURL) 
     print("-------") 
     print(webView.request?.url?.absoluteString) 
     print("-------") 
     print(webView.stringByEvaluatingJavaScript(from: "window.location.href")) 
    } 
} 
+0

感謝您的詳細回覆! webViewDidFinishLoad函數完美地工作,每當我瀏覽到webview中的新網站時,我都能夠接收到頁面的URL。 –

0

嘗試刪除 「請求」,並使用下列內容:

讓CURRENTURL:的NSString = RootView.URL .absoluteString