很多APP加載webView頁面的時候都有進度條顯示,今天我們這里主要使用相對輕量級的WKWebView加載網頁,至于WKWebView 和UIWebView的區別與聯系這里就不多講了,自己百度哈哈。。。
WKWebView加載網頁進度跳顯示主要效果如下:
這里主要是使用KVO監聽WKWebView的“estimatedProgress”屬性,通過監聽該屬性的變化才是進度條的長度。
1、定義便利構造函數、以及屬性和控件
var url: String? var progresslayer = CALayer() var webView: WKWebView? var button: UIButton?convenience init(title: String, url: String) { self.init() self.title = title self.url = url }
2、創建webview控件,并監聽estimatedProgress,進度條初始化的時候會給一定的長度顯示(原因下面解釋)。
func setupUI() { webView = WKWebView(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: screenHeight-64.0)) if url == "" { url = "http:www.baidu.com" } let request = URLRequest(url: URL(string: url ?? "http:www.baidu.com")!) webView?.load(request) webView?.uiDelegate = self webView?.navigationDelegate = self; view.addSubview(webView!) //添加屬性監聽 webView?.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) progresslayer.frame = CGRect.init(x: 0, y: 0, width: screenWidth * 0.1, height: 3) progresslayer.backgroundColor = UIColor.green.cgColor view.layer.addSublayer(progresslayer) }
3、監聽estimatedProgress屬性變化,并修改進度條長度,創建進度條的時候之所以給一定的默認長度主要是因為在沒有網絡的狀態下會立即進度float == 1條件,這樣給人的感覺就是沒有加載網頁一樣。
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "estimatedProgress" { progresslayer.opacity = 1 let float = (change?[NSKeyValueChangeKey.newKey] as! NSNumber).floatValue progresslayer.frame = CGRect.init(x: 0, y: 0, width: (screenWidth * CGFloat(float)) , height: 3) if float == 1 { weak var weakself = self DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2, execute: { weakself?.progresslayer.opacity = 0 }) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8, execute: { weakself?.progresslayer.frame = CGRect.init(x: 0, y: 0, width: 0, height: 3); }) } }else{ super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } }
4、web view加載失敗后提示
extension KKWebView : WKUIDelegate, WKNavigationDelegate { func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { guard let btn = button else { button = UIButton(type: .system) button?.frame = CGRect.init(x: 0, y: 3, width: screenWidth, height: screenHeight-64-3) button?.backgroundColor = UIColor.white button?.setTitleColor(UIColor.darkText, for: .normal) button?.setTitle("點擊重新加載", for: .normal) button?.addTarget(self, action: #selector(loadURL), for: .touchUpInside) view.addSubview(button!) return } btn.isHidden = false }}
5、記載失敗后點擊提示重新加載
func loadURL() { button?.isHidden = true if url == "" { url = "http:www.baidu.com" } let request = URLRequest(url: URL(string: url ?? "http:www.baidu.com")!) webView?.load(request) }
5、移除監聽,離開頁面的時候需要移除KVO監聽,否則會出現內存泄露
deinit { webView!.removeObserver(self, forKeyPath: "estimatedProgress") }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答