import UIKit
import WebKit
@objcMembers
class BaseWebViewController: BaseViewController,WKUIDelegate, WKNavigationDelegate {
private var webView:WKWebView?
private let urlString: String
private lazy var progressView: UIProgressView = {
var progressView = UIProgressView.init(frame: CGRect(x: CGFloat(0), y: CGFloat(ScreenInfo.navigationHeight + 1), width: UIScreen.main.bounds.width, height: 2))
progressView.tintColor = UIColor.x00FF00 // 进度条颜色
progressView.trackTintColor = UIColor.xFFFFFF // 进度条背景色
return progressView
}()
init(urlString: String,title: String,showCloseButton: Bool = true) {
self.urlString = urlString
print(urlString)
super.init(title:title,showCloseButton: showCloseButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setUpWKwebView()
}
// setUpWKwebView
private func setUpWKwebView() {
if self.webView == nil {
self.webView = WKWebView(frame: self.view.frame)
}
let url = URL(string:urlString)
if let url = url {
self.webView!.load(URLRequest(url: url))
}
self.view.addSubview(self.webView!)
self.view.addSubview(progressView)
self.webView!.uiDelegate = self
self.webView!.navigationDelegate = self
self.webView!.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// 加载进度条
if keyPath == "estimatedProgress"{
progressView.alpha = 1.0
progressView.setProgress(Float((self.webView?.estimatedProgress) ?? 0), animated: true)
if (self.webView?.estimatedProgress ?? 0.0) >= 1.0 {
UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {
self.progressView.alpha = 0
}, completion: { (finish) in
self.progressView.setProgress(0.0, animated: false)
})
}
}
}
// MARK: - WKNavigationDelegate
//页面开始加载时调用
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){
}
//当在开始加载数据时发生错误
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
MBProgressHud.showErrorMessage(message: "loadingFail".localizedString())
}
//当内容开始返回时调用
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
}
// 页面加载完成之后调用
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
}
//页面加载失败时调用
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
MBProgressHud.showErrorMessage(message: "loadingFail".localizedString())
}
// MARK: - WKUIDelegate
func webViewDidClose(_ webView: WKWebView) {
}
// MARK: - didReceiveMemoryWarning
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - deinit
deinit {
self.webView?.removeObserver(self, forKeyPath: "estimatedProgress")
self.webView?.uiDelegate = nil
self.webView?.navigationDelegate = nil
}
}