前言
開發(fā) App 的過程中,常常會遇到在 App 內(nèi)部加載網(wǎng)頁,通常用 UIWebView 加載。iOS 8.0 和 OS X 10.10 以后,蘋果推出了新框架 Webkit(使用時導(dǎo)入<WebKit/WebKit.h>),提供了替換UIWebView 的組件 WKWebView。使用WKWebView最為明顯的有點事內(nèi)存占用比UIWebView內(nèi)存占用小很多,我做過一個對比,用兩個控件加載我們的同一個H5頁面,使用 UIWebView 內(nèi)存增加了20M多,而使用 WKWebView 只增加了1M多。自己可以動手試試做個比較。也有很多人說在加載速度上有提升,本人測試了一下,在加載時間上并沒有明顯的提升。官方文檔是這樣描述的
Important
Starting in iOS 8.0 and OS X 10.10, use WKWebView to add web content to your app. Do not use UIWebView or WebView.
很明顯在 iOS 8.0 和 OS X 10.10 以后,蘋果官方推薦使用 WKWebView,而不是 UIWebView 或 WebView,所以使用 WKWebView 是一種趨勢,下面說說 WKWebView 的介紹和使用。

簡介
- 更多的支持 HTML5 的特性
- 官方宣稱的高達(dá)60fps的滾動刷新率以及內(nèi)置手勢
- 與 Safari 相同的 JavaScript 引擎
- 將 UIWebViewDelegate 與 UIWebView 拆分成了14個類與3個協(xié)議(Webkit 官方文檔說明)
- 增加加載進(jìn)度屬性:estimatedProgress

Class
- WKBackForwardList: 之前訪問過的 web 頁面的列表,可以通過后退和前進(jìn)動作來訪問到。
- WKBackForwardListItem: webview 中后退列表里的某一個網(wǎng)頁。
- WKFrameInfo: 包含一個網(wǎng)頁的布局信息。
- WKNavigation: 包含一個網(wǎng)頁的加載進(jìn)度信息。
- WKNavigationAction: 包含可能讓網(wǎng)頁導(dǎo)航變化的信息,用于判斷是否做出導(dǎo)航變化。
- WKNavigationResponse: 包含可能讓網(wǎng)頁導(dǎo)航變化的返回內(nèi)容信息,用于判斷是否做出導(dǎo)航變化。
- WKPreferences: 概括一個 webview 的偏好設(shè)置。
- WKProcessPool: 表示一個 web 內(nèi)容加載池。
- WKUserContentController: 提供使用 JavaScript post 信息和注射 script 的方法。
- WKScriptMessage: 包含網(wǎng)頁發(fā)出的信息。
- WKUserScript: 表示可以被網(wǎng)頁接受的用戶腳本。
- WKWebViewConfiguration: 初始化 webview 的設(shè)置。
- WKWindowFeatures: 指定加載新網(wǎng)頁時的窗口屬性。
- WKWebsiteDataStore: 包含網(wǎng)頁數(shù)據(jù)存儲和查找。
Protocols
- WKNavigationDelegate: 提供了追蹤主窗口網(wǎng)頁加載過程和判斷主窗口和子窗口是否進(jìn)行頁面加載新頁面的相關(guān)方法。
- WKUIDelegate: 提供用原生控件顯示網(wǎng)頁的方法回調(diào)。
- WKScriptMessageHandler: 提供從網(wǎng)頁中收消息的回調(diào)方法。
WKWebView中的三個代理
1. WKNavigationDelegate
// ******* 頁面跳轉(zhuǎn)的代理方法有三種,分為(收到跳轉(zhuǎn)與決定是否跳轉(zhuǎn)兩種) *******
// 在發(fā)送請求之前,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
NSString *method = NSStringFromSelector(_cmd);
NSLog(@"在發(fā)送請求之前,決定是否跳轉(zhuǎn) ******* %@ *******", method);
// 在請求加載前決定是否繼續(xù)加載當(dāng)前請求
//decisionHandler(WKNavigationActionPolicyCancel);
decisionHandler(WKNavigationActionPolicyAllow);
}
// 接收到服務(wù)器跳轉(zhuǎn)請求之后調(diào)用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
NSString *method = NSStringFromSelector(_cmd);
NSLog(@"接收到服務(wù)器跳轉(zhuǎn)請求之后調(diào)用 ******* %@ *******", method);
}
// 在收到響應(yīng)后,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
decisionHandler(WKNavigationResponsePolicyAllow);
NSString *method = NSStringFromSelector(_cmd);
NSLog(@"在收到響應(yīng)后,決定是否跳轉(zhuǎn) ******* %@ *******", method);
}
// ******* 用來追蹤加載過程(頁面開始加載、加載完成、加載失?。? *******
// 頁面開始加載時調(diào)用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
NSString *method = NSStringFromSelector(_cmd);
NSLog(@"頁面開始加載 ******* %@ *******", method)
}
// 當(dāng)內(nèi)容開始返回時調(diào)用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
NSString *method = NSStringFromSelector(_cmd);
NSLog(@"內(nèi)容開始返回 ******* %@ *******", method)
}
// 頁面加載完成之后調(diào)用(有時候此方法執(zhí)行特別慢)
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
NSString *method = NSStringFromSelector(_cmd);
NSLog(@"頁面加載完成 ******* %@ *******", method)
NSString *url = [webView.URL absoluteString];
NSString *title = webView.title;
// 注意:此方法有時候會執(zhí)行特別慢,由于我在此方法里需要獲取 webView.title 并設(shè)置導(dǎo)航欄的 title,導(dǎo)致有時候出現(xiàn)導(dǎo)航欄標(biāo)題顯示很慢,給人的錯覺是標(biāo)題為空
// 解決辦法:讓H5加載的時候,H5調(diào)用我們native的一個方法,讓他們?nèi)ピO(shè)置我們導(dǎo)航欄的 title,此處涉及到了 OC 與 JS 的交互,后面會講到
NSLog(@"title = %@, url = %@", title, url);
}
2. WKUIDelegate
- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
NSString *method = NSStringFromSelector(_cmd);
NSLog(@"創(chuàng)建一個新的webView時調(diào)用 ******* %@ *******", method);
if (!navigationAction.targetFrame.isMainFrame) {
[webView loadRequest:navigationAction.request];
}
return nil;
}
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
NSString *method = NSStringFromSelector(_cmd);
NSLog(@"界面彈出警告框時調(diào)用 ******* %@ *******", method);
//[self showMsg:message];
NSLog(@"message = %@", message);
completionHandler();
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler
{
NSString *method = NSStringFromSelector(_cmd);
NSLog(@"界面彈出確認(rèn)框時調(diào)用 ******* %@ *******", method);
//[self showMsg:message];
NSLog(@"message = %@", message);
completionHandler(YES);
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler
{
NSString *method = NSStringFromSelector(_cmd);
NSLog(@"界面彈出輸入框時調(diào)用 ******* %@ *******", method);
}
注:在iOS 9 和 iOS 10 的時候添加了新的方法,這里就不一一舉例了,有興趣的同學(xué)自己去研究下。
3. WKScriptMessageHandler
這個協(xié)議中包含一個必須實現(xiàn)的方法,這個方法是 native 與 web 端交互的關(guān)鍵,它可以直接將接收到的 JS 腳本轉(zhuǎn)為 OC 或 Swift 對象。
@required
/*! @abstract Invoked when a script message is received from a webpage.
@param userContentController The user content controller invoking the
delegate method.
@param message The script message received.
*/
#pragma mark - WKScriptMessageHandler -
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
if ([message.name isEqualToString:@"testMethod1"]) {
NSString *info = [NSString stringWithFormat:@"字符串:%@", message.body];
NSLog(@"JS 調(diào)用 Native 的 testMethod1 方法,傳遞的參數(shù)是 %@", info);
}
if ([message.name isEqualToString:@"testMethod2"]) {
NSArray *array = message.body;
NSString *info = [NSString stringWithFormat:@"數(shù)組:元素1:%@ 元素2:%@", array.firstObject, array.lastObject];
NSLog(@"JS 調(diào)用 Native 的 testMethod2 方法,傳遞的參數(shù)是 %@", info);
}
}
// 與此協(xié)議配合使用的(其實就是聲明 Native 有方法 testMethod1 和 testMethod2)
[_webView.configuration.userContentController addScriptMessageHandler:self name:@"testMethod1"];
[_webView.configuration.userContentController addScriptMessageHandler:self name:@"testMethod2"];
// JS 端代碼如下
//window.webkit.messageHandlers.testMethod1.postMessage('冬冬是冬瓜')
//window.webkit.messageHandlers.testMethod2.postMessage(['涂冬冬是冬冬', '徐冬冬也是冬冬'])
// 注意:在頁面消失的時候,記得調(diào)用下面方法,否則會導(dǎo)致內(nèi)存泄漏
[_webView.configuration.userContentController removeScriptMessageHandlerForName:@"testMethod1"];
[_webView.configuration.userContentController removeScriptMessageHandlerForName:@"testMethod2"];
填坑
1. 關(guān)于 Cookie
在使用的時候由于需求,需要在 webView 中設(shè)置 Cookie,天真的我一如既往的就這么做了,代碼如下??:
// 添加 Cookie
- (void)configCookie
{
NSDictionary *inAppDic = @{NSHTTPCookieName:@"test_inApp",
NSHTTPCookieValue:@"1",
NSHTTPCookieDomain:@".test.com",
NSHTTPCookiePath:@"/"};
NSHTTPCookie *cookieInApp = [NSHTTPCookie cookieWithProperties:inAppDic];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieInApp];
NSDictionary *appVersionDic = @{NSHTTPCookieName:@"test_appVersion",
NSHTTPCookieValue:@"2.8.9",
NSHTTPCookieDomain:@".test.com",
NSHTTPCookiePath:@"/"};
NSHTTPCookie *cookieAppVersion = [NSHTTPCookie cookieWithProperties:appVersionDic];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieAppVersion];
}
// 刪除 Cookie
- (void)deleteCookie
{
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies]) {
if ([cookie.name isEqualToString:@"test_inApp"] || [cookie.name isEqualToString:@"test_appVersion"]) {
[storage deleteCookie:cookie];
}
}
}
事實證明:使用 WKWebView 時,這樣設(shè)置 Cookie 是無效的。查了很多資料,主要有如下兩種設(shè)置 Cookie 的方法。
方法一:在 WKWebView 加載請求的時候在請求頭中注入 Cookie (針對于服務(wù)端)
- (void)configCookieWithRequest:(NSMutableURLRequest *)request
{
[self configCookie];
if (request.URL) {
// 方法1(從NSHTTPCookieStorage中獲取,手動添加到請求頭中)
NSDictionary *cookiesDic = [NSHTTPCookie requestHeaderFieldsWithCookies:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL]];
if ([cookiesDic objectForKey:@"Cookie"]) {
[request addValue:cookiesDic[@"Cookie"] forHTTPHeaderField:@"Cookie"];
}
// log: = {Cookie:test_inApp=1; test_appVersion=2.8.9}
// 方法2(直接拼接好Cookie字符串,添加到請求頭中)
NSString *cookieStr = nil;
NSString *cookieInApp = @"test_inApp=1";
cookieStr = [NSString stringWithFormat:@"%@", cookieInApp];
//[request addValue:cookieInApp forHTTPHeaderField:@"Cookie"];
NSString *cookieAppVersion = [NSString stringWithFormat:@"test_appVersion=%@", @"2.8.9"];
cookieStr = [NSString stringWithFormat:@"%@; %@", cookieStr, cookieAppVersion];
//[request addValue:cookieAppVersion forHTTPHeaderField:@"Cookie"];
// 切忌不要多次使用 addValue 方法添加 NSString 類型的 Cookie 字符串,這樣生成的 Cookie 字符串是以 "," 號分隔的,注意上面??方法1中的 cookiesDic[@"Cookie"] 是 NSHTTPCookie 類型是不存在此問題的,對比兩者的不同。
// log: = {Cookie:test_inApp=1,test_appVersion=2.8.9}
// 此處也可使用 addValue 方法添加
//[request addValue:cookieStr forHTTPHeaderField:@"Cookie"];
[request setValue:cookieStr forHTTPHeaderField:@"Cookie"];
// 正確的是以 ";" 號分隔
// log: = {Cookie:test_inApp=1; test_appVersion=2.8.9}
}
NSDictionary *dic = request.allHTTPHeaderFields;
NSLog(@"allHTTPHeaderFields = %@", dic);
}
方法二:在 JS 中注入 Cookie (針對于本地)
- (void)configCookieScript
{
// 將所有 Cookie 以 document.cookie = 'key=value'; 形式進(jìn)行拼接
NSString *cookieInApp = @"test_inApp =1";
NSString *cookieAppVersion = [NSString stringWithFormat:@"test_appVersion =%@", @"2.8.9"];
NSString *cookieValue = [NSString stringWithFormat:@"document.cookie = '%@'; document.cookie = '%@'", cookieInApp, cookieAppVersion];
WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:cookieValue injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[_webView.configuration.userContentController addUserScript:cookieScript];
}
對于以上兩種方式添加 Cookie 其實意義是不一樣的,第一種是針對于服務(wù)端在請求頭中添加,第二種是針對于本地,直接在 JS 中注入。根據(jù)需求可以配合使用,如果 H5 頁面只取服務(wù)端的 Cookie 則使用第一種添加方法;如果只取本地的 Cookie 則使用第二種方法即可,如果都取的話,則兩種一起使用,不過個人建議還是做個 Cookie 同步,即用第一種方法添加完后再使用第二種方法同步添加到本地。
2. 關(guān)于 緩存
在 WKWebsiteDataStore 出現(xiàn)之前(iOS 9 中才出現(xiàn)),WKWebView 是沒有緩存,也無從清理。WKWebView 是基于 WebKit 框架的,它會忽視先前使用的網(wǎng)絡(luò)存儲 NSURLCache, NSHTTPCookieStorage, NSCredentialStorage等,它也有自己的存儲空間用來存儲cookie和cache,其他的網(wǎng)絡(luò)類如NSURLConnection 是無法訪問到的。
// 清理緩存
- (void)removeWebViewDataCache
{
if (IOS_GREATER_THAN_OR_EQUAL_TO(@"9.0")) {
// iOS 9 以后終于可以使用 WKWebsiteDataStore 來清理緩存
NSSet *types = [NSSet setWithArray:@[WKWebsiteDataTypeDiskCache,
WKWebsiteDataTypeMemoryCache,
//WKWebsiteDataTypeCookies,
]];
NSDate *dateFrom = [NSDate date];
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:types modifiedSince:dateFrom completionHandler:^{
NSLog(@"clear webView cache");
}];
}
else {
// iOS 8 可以通過清理 Library 目錄下的 Cookies 目錄來清除緩存
NSString *libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
[[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:nil];
}
}
目前就遇到這些,以后有新坑接著填坑。