iOS WKWebView实现网页加载进度条(Swift3.0)

iOS WKWebView实现网页加载进度条(Swift3.0)_第1张图片
Simulator Screen Shot004.png
WKWebView是iOS8 WebKit框架下控件,WKWebView 的estimatedProgress是当前网页加载进度,可以监听此属性。
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
以下是实现代码:
import UIKit
import WebKit

class LmyWebController: UIViewController,WKNavigationDelegate,WKUIDelegate {
    private var webView = WKWebView()
    private var progressView = UIProgressView()
    var open_url:String = "https://www.apple.com/cn/"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        // Do any additional setup after loading the view.
        webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.height))
        webView.navigationDelegate = self
        webView.uiDelegate = self;
        let url = URL(string: open_url)
        let request = URLRequest(url: url!)
        webView.load(request)
        /**
         增加的属性:
         1.webView.estimatedProgress加载进度
         2.backForwardList 表示historyList
         3.WKWebViewConfiguration *configuration; 初始化webview的配置
         */
        self.view.addSubview(webView)
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        
        progressView = UIProgressView(frame: CGRect(x: 0, y: 44-2, width: UIScreen.main.bounds.size.width, height: 2))
        progressView.trackTintColor = UIColor.white
        progressView.progressTintColor = UIColor.orange
        self.navigationController?.navigationBar.addSubview(progressView)
        
        let item = UIBarButtonItem(title: "<--", style: .plain, target: self, action: #selector(backItemPressed))
        self.navigationItem.leftBarButtonItem = item
    }
    func backItemPressed() {
        if webView.canGoBack {
            webView.goBack()
        }else{
            if let nav = self.navigationController {
                nav.popViewController(animated: true)
            }
        }
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if (keyPath == "estimatedProgress") {
            progressView.isHidden = webView.estimatedProgress == 1
            progressView.setProgress(Float(webView.estimatedProgress), animated: true)
            print(webView.estimatedProgress)
        }
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        progressView.setProgress(0.0, animated: false)
        self.navigationItem.title = webView.title
    }
}
最后,别忘了移除观察者:
deinit {
    print("con is deinit")
    webView.removeObserver(self, forKeyPath: "estimatedProgress")
    progressView.reloadInputViews()
}
结束

你可能感兴趣的:(iOS WKWebView实现网页加载进度条(Swift3.0))