Webkit 是 iOS 8.0 后提供的新的框架,组件WKWebView比较UIWebView 速度更快、占用内存更少了,可支持性更多
WKWebView可通过KVO监听属性 title、estimaredProgress、hasOnlySecureContent
estimatedProgress: 当前navigation加载的进度,加载进度包括主要文档和其他的子资源文件
hasOnlySecureContent:加载的网页的所有资源是否通过安全编码链接加载的
webView?.addObserver(self, forKeyPath: "title", options: .new, context: nil) 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 == "title" { }else if keyPath == "estimatedProgress"{ let estimatedProgress = Float((self.webView?.estimatedProgress)!) self.progressView?.setProgress(estimatedProgress, animated: true) }else{ super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } }
WKWebViewConfiguration : WKWebView初始化时可设置的配置化信息,可设置偏好信息,设置js与WebView交互
let configuration = WKWebViewConfiguration() //偏好设置 configuration.preferences = WKPreferences.init() configuration.preferences.minimumFontSize = 16 configuration.preferences.javaScriptEnabled = true //内容处理池 configuration.processPool = WKProcessPool.init() // 通过js与WebView交互 configuration.userContentController = WKUserContentController.init()
//WKUserContentController 向webView提供发送js 信息的桥梁
// 调用js webView.evaluateJavaScript("showAlert('调用js 弹窗')") { (itme, error) in }
页面加载前回调代理:
// 打开网页前判断是否跳转代理 // WKNavigationAction 包含了请求网页过程的信息 判断是否允许跳转 // sourceFrame // targetFrame,分别代表这个action的出处和目标.navigationAction.targetFrame?.isMainFrame 可判断是否新开页面跳转 // WKNavigationType: // case linkActivated //链接href被激活 // // case formSubmitted //一个表单的提交 // // case backForward // // case reload //网页加载 // // case formResubmitted //表单提交 // // case other func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { decisionHandler(WKNavigationActionPolicy.allow) }