1.利用WKWebView在app内嵌入网页
在loadView()中设置view
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
view = webView
}
2.加载页面方法
let url = URL(string: "https://www.baidu.com")!
webView.load(URLRequest(url: url))
//允许右滑返回的手势
webView.allowsBackForwardNavigationGestures = true
3.WKNavigationDelegate
页面跳转的代理方法
//发送请求之前决定是否跳转
optional public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void)
//收到响应之后决定是否跳转
optional public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void)
// 接收到服务器跳转请求之后调用
optional public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!)
加载的状态回调
//页面开始加载时候调用
optional public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)
//页面内容开始返回的时候调用
optional public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!)
//加载完成后调用
optional public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
//加载失败后调用
optional public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error)
4.利用KVO监测webView加载的进度
添加观察器
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
实现监测方法
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(WKWebView.estimatedProgress) {
progressView.progress = Float(webView.estimatedProgress)
}
}
移除观察器
deinit {
webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
}
- @escaping 和@noesacpe注解
func hostFunc(@noescape closure: () -> ()) -> Void {
//以下编译出错, closure 被修饰后, 不能被其他异步线程捕获
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
closure()
}
}
@noescape字面意思是无法逃脱. 在上例中, closure 被@noescape修饰, 则声明 closure 的生命周期不能超过 hostFunc, 并且, closure不能被hostFunc中的其他闭包捕获
@escaping就是可以逃逸的意思,在当前func执行完毕的时候并不影响这个闭包的执行。