一、创建,我们可以在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进行交互
网友评论