# 13.UIWebView和WKWebView

## 一: UIWebView的优缺点

### 优点

* 支持缓存和NSURLProtocol拦截

### 缺点

* 内存泄露
* 加载大数据资源时内存占用大,耗电量高

## 二: WKWebView的优缺点

### 优点

* 加载网页速度提升,内存占用低(UIWebView的1/3 \~ 1/4)
* 提供加载网页进度的属性
* 拥有高达60FPS滚动刷新率及内置手势
* 高效的App和web信息交换通道

### 缺点

* 没有缓存(WKWebsiteDataStore - iOS9之后)
* 不支持NSURLProtocol拦截(可通过私有方法实现桥接)
  * 拦截的POST数据不完整基本等于没用

### 资源代理

* iOS11开始 `WKURLSchemeHandler` 可用来加载自定义资源
* 注意：
  * setURLSchemeHandler注册时机只能在WKWebView创建WKWebViewConfiguration时注册。
  * WKWebView 只允许开发者拦截自定义 Scheme 的请求，不允许拦截 “http”、“https”、“ftp”、“file” 等的请求，否则会crash。
  * WKWebView加载网页前，要在user-agent添加个标志，H5遇到这个标识就使用customScheme,否则就是用原来的http或https。

## 三: Cookie

* WKWebView 上请求不会自动携带 Cookie ，解决方案是 loadRequest 时，从 NSHTTPCookieStorage 中获取对应的 cookie，通过 WKUserScript 设置到 WKWebView 界面中的 document.cookies 中，
* 注意的是，注入 cookie 的脚本执行时机需要设置为 WKUserScriptInjectionTimeAtDocumentStart 。

## 四: 跨域

* WebKit框架对跨域进行了安全性检查限制，不允许跨域，比如从一个 `HTTP` 页对 `HTTPS` 发起请求是无效的(Safari支持)
* 解决办法
  * 在该方法中特殊处理

```
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
```

![](https://upload-images.jianshu.io/upload_images/1200910-1039aa39914f2e79.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/873)

## 参考

> <https://www.jianshu.com/p/90a90bd13aac>
>
> iOS App秒开H5优化总结
>
> > <https://mp.weixin.qq.com/s?__biz=MzA5NzMwODI0MA==&mid=2647762931&idx=1&sn=ce6e47875d8d278110fca1f18fec6f28&chksm=8887dcccbff055da059008e463bb26829dbb94ad7b94d1bf7f70231060498388832fc7f3d75c&scene=21#wechat_redirect>
>
> iOS App秒开H5实战总结
>
> > <https://mp.weixin.qq.com/s/1Rfizwcn9EV2rby0btSMaw>
>
> WKWebVIew那些坑
>
> > <https://mp.weixin.qq.com/s?__biz=MzA3NTYzODYzMg==&mid=2653578513&idx=1&sn=961bf5394eecde40a43060550b81b0bb&scene=21#wechat_redirect>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/ios/za-xiang/uiwebview-he-wkwebview.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
