Swift WKWebView(一):基本使用
阿新 • • 發佈:2018-11-03
一、建立,我們可以在Viewcontroller
中使用如下的懶載入的方式建立一個WKWebView
以及一個便於觀察進度的進度條:
// wkWebView
lazy var wkWebView = WKWebView()
// 進度條
lazy var progressView = UIProgressView()
隨後我們可以在
viewDidLoad
實現方法,將這兩個控制元件新增到檢視中,在這裡要注意iphone機型的的適配,程式碼如下:
override func viewDidLoad() { super.viewDidLoad() initInterface() } func initInterface() -> () { self.wkWebView.frame = CGRect(x: safeAreaInsets.left , y: safeAreaInsets.top + 44 , width: ScreenWidth , height: ScreenHeight - safeAreaInsets.top - 44 - safeAreaInsets.bottom) let url = URL(string: "https://blog.csdn.net/kmonarch/article/details/82753235") let request = URLRequest(url: url!) wkWebView.navigationDelegate = self wkWebView.load(request) self.view.addSubview(self.wkWebView) self.progressView.frame = CGRect(x: safeAreaInsets.left , y: safeAreaInsets.top + 44 , width: ScreenWidth , height: 2) progressView.progressTintColor = UIColor.red progressView.trackTintColor = UIColor.clear self.view.addSubview(self.progressView) }
二、實現代理方法
extension TestViewController: WKNavigationDelegate { // 監聽網頁載入進度 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { self.progressView.progress = Float(self.wkWebView.estimatedProgress) } // 頁面開始載入時呼叫 func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { Log4jMessage(message: "開始載入...") } // 當內容開始返回時呼叫 func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){ Log4jMessage(message: "當內容開始返回...") } // 頁面載入完成之後呼叫 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){ Log4jMessage(message: "頁面載入完成...") /// 獲取網頁title self.title = self.wkWebView.title UIView.animate(withDuration: 0.5) { self.progressView.isHidden = true } } // 頁面載入失敗時呼叫 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){ Log4jMessage(message: "頁面載入失敗...") UIView.animate(withDuration: 0.5) { self.progressView.progress = 0.0 self.progressView.isHidden = true } /// 彈出提示框點選確定返回 let alertView = UIAlertController.init(title: "提示", message: "載入失敗", preferredStyle: .alert) let okAction = UIAlertAction.init(title:"確定", style: .default) { okAction in _=self.navigationController?.popViewController(animated: true) } alertView.addAction(okAction) self.present(alertView, animated: true, completion: nil) } }
在下一章中將探討使用WkWebView與h5進行互動