基础代码
import UIKit
import WebKit
class ViewController: UIViewController,WKUIDelegate, WKNavigationDelegate {
lazy private var webview: WKWebView = {
self.webview = WKWebView.init(frame: self.view.bounds)
self.webview.uiDelegate = self as WKUIDelegate
self.webview.navigationDelegate = self as WKNavigationDelegate
return self.webview
}()
lazy private var progressView: UIProgressView = {
self.progressView = UIProgressView.init(frame: CGRect(x: CGFloat(0), y: CGFloat(65), width: UIScreen.main.bounds.width, height: 2))
self.progressView.tintColor = UIColor.red
self.progressView.trackTintColor = UIColor.white
return self.progressView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(webview)
view.addSubview(progressView)
webview.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
webview.load(URLRequest.init(url: URL.init(string: "https://www.baidu.com/")!)) }
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "estimatedProgress"{
progressView.alpha = 1.0
progressView.setProgress(Float(webview.estimatedProgress), animated: true)
if webview.estimatedProgress >= 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)
})
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
deinit {
webview.removeObserver(self, forKeyPath: "estimatedProgress")
webview.uiDelegate = nil
webview.navigationDelegate = nil
}
}
更多代码,例如查看状态
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { print("开始加载")
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
print("开始获取网页内容")
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("加载完成")
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print("加载失败")
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
decisionHandler(.allow);
}