導語
WKWebView 是蘋果在 WWDC 2014 上推出的新一代 webView 組件克滴,用以替代 UIKit 中笨重難用篇裁、內存泄漏的 UIWebView跑揉。WKWebView 擁有60fps滾動刷新率待讳、和 safari 相同的 JavaScript 引擎等優(yōu)勢品擎。
簡單的適配方法本文不再贅述罕拂,主要來說說適配 WKWebView 過程中填過的坑以及善待解決的技術難題揍异。
1、WKWebView 白屏問題
WKWebView 自詡擁有更快的加載速度爆班,更低的內存占用衷掷,但實際上 WKWebView 是一個多進程組件,Network Loading 以及 UI Rendering 在其它進程中執(zhí)行柿菩。初次適配 WKWebView 的時候戚嗅,我們也驚訝于打開 WKWebView 后,App 進程內存消耗反而大幅下降枢舶,但是仔細觀察會發(fā)現(xiàn)懦胞,Other Process 的內存占用會增加。在一些用 webGL 渲染的復雜頁面凉泄,使用 WKWebView 總體的內存占用(App Process Memory + Other Process Memory)不見得比 UIWebView 少很多躏尉。
在 UIWebView 上當內存占用太大的時候,App Process 會 crash后众;而在 WKWebView 上當總體的內存占用比較大的時候醇份,WebContent Process 會 crash稼锅,從而出現(xiàn)白屏現(xiàn)象。在 WKWebView 中加載下面的測試鏈接可以穩(wěn)定重現(xiàn)白屏現(xiàn)象:
http://people.mozilla.org/~rnewman/fennec/mem.html
這個時候 WKWebView.URL 會變?yōu)?nil, 簡單的 reload 刷新操作已經失效僚纷,對于一些長駐的H5頁面影響比較大。
我們最后的解決方案是:
A拗盒、借助 WKNavigtionDelegate
iOS 9以后 WKNavigtionDelegate 新增了一個回調函數(shù):
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webViewAPI_AVAILABLE(macosx(10.11),ios(9.0));
當 WKWebView 總體內存占用過大怖竭,頁面即將白屏的時候,系統(tǒng)會調用上面的回調函數(shù)陡蝇,我們在該函數(shù)里執(zhí)行[webView reload](這個時候 webView.URL 取值尚不為 nil)解決白屏問題痊臭。在一些高內存消耗的頁面可能會頻繁刷新當前頁面,H5側也要做相應的適配操作登夫。
B广匙、檢測 webView.title 是否為空
并不是所有H5頁面白屏的時候都會調用上面的回調函數(shù),比如恼策,最近遇到在一個高內存消耗的H5頁面上 present 系統(tǒng)相機鸦致,拍照完畢后返回原來頁面的時候出現(xiàn)白屏現(xiàn)象(拍照過程消耗了大量內存,導致內存緊張涣楷,WebContent Process 被系統(tǒng)掛起)分唾,但上面的回調函數(shù)并沒有被調用。在WKWebView白屏的時候狮斗,另一種現(xiàn)象是 webView.titile 會被置空, 因此绽乔,可以在 viewWillAppear 的時候檢測 webView.title 是否為空來 reload 頁面。
綜合以上兩種方法可以解決絕大多數(shù)的白屏問題碳褒。
2折砸、WKWebView Cookie 問題
Cookie 問題是目前 WKWebView 的一大短板
2.1、WKWebView Cookie存儲
業(yè)界普遍認為 WKWebView 擁有自己的私有存儲沙峻,不會將 Cookie 存入到標準的 Cookie 容器NSHTTPCookieStorage中睦授。
實踐發(fā)現(xiàn) WKWebView 實例其實也會將 Cookie 存儲于 NSHTTPCookieStorage 中,但存儲時機有延遲专酗,在iOS 8上睹逃,當頁面跳轉的時候,當前頁面的 Cookie 會寫入 NSHTTPCookieStorage 中祷肯,而在 iOS 10 上沉填,JS 執(zhí)行 document.cookie 或服務器 set-cookie 注入的 Cookie 會很快同步到 NSHTTPCookieStorage 中,F(xiàn)ireFox 工程師曾建議通過 reset WKProcessPool 來觸發(fā) Cookie 同步到 NSHTTPCookieStorage 中佑笋,實踐發(fā)現(xiàn)不起作用翼闹,并可能會引發(fā)當前頁面 session cookie 丟失等問題。
WKWebView Cookie 問題在于 WKWebView 發(fā)起的請求不會自動帶上存儲于 NSHTTPCookieStorage 容器中的 Cookie蒋纬。
比如猎荠,NSHTTPCookieStorage 中存儲了一個 Cookie:
name=Nicholas;value=test;domain=y.qq.com;expires=Sat,02 May201923:38:25 GMT坚弱;
通過 UIWebView 發(fā)起請求http://y.qq.com,則請求頭會自動帶上 cookie: Nicholas=test关摇;
而通過 WKWebView發(fā)起請求http://y.qq.com荒叶,請求頭不會自動帶上 cookie: Nicholas=test。
2.2输虱、WKProcessPool
蘋果開發(fā)者文檔對 WKProcessPool 的定義是:A WKProcessPool object represents a pool of Web Content process. 通過讓所有 WKWebView 共享同一個 WKProcessPool 實例些楣,可以實現(xiàn)多個 WKWebView 之間共享 Cookie(session Cookie and persistent Cookie)數(shù)據(jù)。不過 WKWebView WKProcessPool 實例在 app 殺進程重啟后會被重置宪睹,導致 WKProcessPool 中的 Cookie愁茁、session Cookie 數(shù)據(jù)丟失,目前也無法實現(xiàn) WKProcessPool 實例本地化保存亭病。
2.3鹅很、Workaround
由于許多 H5 業(yè)務都依賴于 Cookie 作登錄態(tài)校驗,而 WKWebView 上請求不會自動攜帶 Cookie, 目前的主要解決方案是:
a罪帖、WKWebView loadRequest 前促煮,在 request header 中設置 Cookie, 解決首個請求 Cookie 帶不上的問題;
WKWebView * webView = [WKWebViewnew];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://h5.qzone.qq.com/mqzone/index"]];
[request addValue:@"skey=skeyValue" forHTTPHeaderField:@"Cookie"];
[webView loadRequest:request];
b胸蛛、通過 document.cookie 設置 Cookie 解決后續(xù)頁面(同域)Ajax污茵、iframe 請求的 Cookie 問題;
注意:document.cookie()無法跨域設置 cookie
WKUserContentController* userContentController = [WKUserContentControllernew];
WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource: @"document.cookie = 'skey=skeyValue';" injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
這種方案無法解決302請求的 Cookie 問題葬项,比如泞当,第一個請求是 www.a.com,我們通過在 request header 里帶上 Cookie 解決該請求的 Cookie 問題民珍,接著頁面302跳轉到 www.b.com襟士,這個時候 www.b.com 這個請求就可能因為沒有攜帶 cookie 而無法訪問。當然嚷量,由于每一次頁面跳轉前都會調用回調函數(shù):
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
可以在該回調函數(shù)里攔截302請求陋桂,copy request,在 request header 中帶上 cookie 并重新 loadRequest蝶溶。不過這種方法依然解決不了頁面 iframe 跨域請求的 Cookie 問題嗜历,畢竟-[WKWebView loadRequest:]只適合加載 mainFrame 請求。
3抖所、WKWebView NSURLProtocol問題
WKWebView 在獨立于 app 進程之外的進程中執(zhí)行網絡請求梨州,請求數(shù)據(jù)不經過主進程,因此田轧,在 WKWebView 上直接使用 NSURLProtocol 無法攔截請求暴匠。蘋果開源的 webKit2 源碼暴露了私有API:
+ [WKBrowsingContextController registerSchemeForCustomProtocol:]
通過注冊 http(s) scheme 后 WKWebView 將可以使用 NSURLProtocol 攔截 http(s) 請求:
Class cls = NSClassFromString(@"WKBrowsingContextController”);
SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
if ([(id)cls respondsToSelector:sel]) {
// 注冊http(s) scheme, 把 http和https請求交給 NSURLProtocol處理
[(id)cls performSelector:sel withObject:@"http"];
[(id)cls performSelector:sel withObject:@"https"];
}
但是這種方案目前存在兩個嚴重缺陷:
a、post 請求 body 數(shù)據(jù)被清空
由于 WKWebView 在獨立進程里執(zhí)行網絡請求傻粘。一旦注冊 http(s) scheme 后每窖,網絡請求將從 Network Process 發(fā)送到 App Process帮掉,這樣 NSURLProtocol 才能攔截網絡請求。在 webkit2 的設計里使用 MessageQueue 進行進程之間的通信窒典,Network Process 會將請求 encode 成一個 Message,然后通過 IPC 發(fā)送給 App Process蟆炊。出于性能的原因,encode 的時候 HTTPBody 和 HTTPBodyStream 這兩個字段被丟棄掉了
參考蘋果源碼:
及bug report:
https://bugs.webkit.org/show_bug.cgi?id=138169(復制鏈接到瀏覽器中打開)
因此瀑志,如果通過 registerSchemeForCustomProtocol 注冊了 http(s) scheme, 那么由 WKWebView 發(fā)起的所有 http(s)請求都會通過 IPC 傳給主進程 NSURLProtocol 處理盅称,導致 post 請求 body 被清空;
b后室、對ATS支持不足
測試發(fā)現(xiàn)一旦打開ATS開關:Allow Arbitrary Loads 選項設置為NO,同時通過 registerSchemeForCustomProtocol 注冊了 http(s) scheme混狠,WKWebView 發(fā)起的所有 http 網絡請求將被阻塞(即便將Allow Arbitrary Loads in Web Content 選項設置為YES)岸霹;
WKWebView 可以注冊 customScheme, 比如 dynamic://, 因此希望使用離線功能又不使用 post 方式的請求可以通過 customScheme 發(fā)起請求,比如 dynamic://www.dynamicalbumlocalimage.com/将饺,然后在 app 進程 NSURLProtocol 攔截這個請求并加載離線數(shù)據(jù)贡避。不足:使用 post 方式的請求該方案依然不適用,同時需要 H5 側修改請求 scheme 以及 CSP 規(guī)則予弧;
4刮吧、WKWebView loadRequest 問題
在 WKWebView 上通過 loadRequest 發(fā)起的 post 請求 body 數(shù)據(jù)會丟失:
//同樣是由于進程間通信性能問題,HTTPBody字段被丟棄
[request setHTTPMethod:@"POST"];[request setHTTPBody:[@"bodyData" dataUsingEncoding:NSUTF8StringEncoding]];
[wkwebview loadRequest: request];
workaround:
假如想通過-[WKWebView loadRequest:]加載 post 請求 request1:http://h5.qzone.qq.com/mqzone/index,可以通過以下步驟實現(xiàn):
替換請求 scheme掖蛤,生成新的 post 請求 request2:post://h5.qzone.qq.com/mqzone/index, 同時將 request1 的 body 字段復制到 request2 的 header 中(WebKit 不會丟棄 header 字段);
通過-[WKWebView loadRequest:]加載新的 post 請求 request2;
通過 +[WKBrowsingContextController registerSchemeForCustomProtocol:]注冊 scheme:post://;
注冊 NSURLProtocol 攔截請求post://h5.qzone.qq.com/mqzone/index,替換請求 scheme, 生成新的請求 request3:http://h5.qzone.qq.com/mqzone/index杀捻,將 request2 header的body 字段復制到 request3 的 body 中,并使用 NSURLConnection 加載 request3蚓庭,最后通過 NSURLProtocolClient 將加載結果返回 WKWebView;
5致讥、WKWebView 頁面樣式問題
在 WKWebView 適配過程中,我們發(fā)現(xiàn)部分H5頁面元素位置向下偏移或被拉伸變形器赞,追蹤后發(fā)現(xiàn)主要是H5頁面高度值異常導致:
a. 空間H5頁面有透明導航垢袱、透明導航下拉刷新、全屏等需求港柜,因此之前 webView 整個是從(0, 0)開始布局请契,通過調整webView.scrollView.contentInset來適配特殊導航欄需求。而在 WKWebView 上對 contentInset 的調整會反饋到webView.scrollView.contentSize.height的變化上夏醉,比如設置webView.scrollView.contentInset.top = a爽锥,那么contentSize.height的值會增加a,導致H5頁面長度增加,頁面元素位置向下偏移授舟;
解決方案是:調整WKWebView布局方式救恨,避免調整webView.scrollView.contentInset。實際上释树,即便在 UIWebView 上也不建議直接調整webView.scrollView.contentInset的值肠槽,這確實會帶來一些奇怪的問題擎淤。如果某些特殊情況下非得調整 contentInset 不可的話,可以通過下面方式讓H5頁面恢復正常顯示:
/**設置contentInset值后通過調整webView.frame讓頁面恢復正常顯示? *參考:http://km.oa.com/articles/show/277372 */
webView.scrollView.contentInset = UIEdgeInsetsMake(a,0,0,0);
webView.frame = CGRectMake(webView.frame.origin.x, webView.frame.origin.y, webView.frame.size.width, webView.frame.size.height - a);
b. 在接入 now 直播的時候秸仙,我們發(fā)現(xiàn)在 iOS 9 上 WKWebView 會出現(xiàn)頁面被拉伸變形的情況嘴拢,最后發(fā)現(xiàn)是window.innerHeight值不準確導致(在WKWebView上返回了一個非常大的值),而H5同學通過獲取window.innerHeight來設置頁面高度寂纪,導致頁面整體被拉伸席吴。通過查閱相關資料發(fā)現(xiàn),這個bug只在 iOS 9 的幾個系統(tǒng)版本上出現(xiàn)捞蛋,蘋果后來fix了這個bug孝冒。我們最后的解決方案是:延遲調用window.innerHeight
setTimeout(function(){height = window.innerHeight},0);
or
Use shrink-to-fit meta-tag
6、WKWebView 截屏問題
空間玩吧H5小游戲有截屏分享的功能拟杉,WKWebView 下通過 -[CALayer renderInContext:]實現(xiàn)截屏的方式失效庄涡,需要通過以下方式實現(xiàn)截屏功能:
@implementation UIView (ImageSnapshot) - (UIImage*)imageSnapshot {? ? UIGraphicsBeginImageContextWithOptions(self.bounds.size,YES,self.contentScaleFactor);? ? [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];? ? UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();? ? UIGraphicsEndImageContext();return newImage; }@end
然而這種方式依然解決不了 webGL 頁面的截屏問題,筆者已經翻遍蘋果文檔搬设,研究過 webKit2 源碼里的截屏私有API穴店,依然沒有找到合適的解決方案,同時發(fā)現(xiàn) Safari 以及 Chrome 這兩個全量切換到 WKWebView 的瀏覽器也存在同樣的問題:對webGL 頁面的截屏結果不是空白就是純黑圖片拿穴。無奈之下泣洞,我們只能約定一個JS接口,讓游戲開發(fā)商實現(xiàn)該接口默色,具體是通過canvas getImageData()方法取得圖片數(shù)據(jù)后返回 base64 格式的數(shù)據(jù)球凰,客戶端在需要截圖的時候,調用這個JS接口獲取 base64 String 并轉換成 UIImage该窗。
7弟蚀、WKWebView crash問題
WKWebView 放量后,外網新增了一些 crash, 其中一類 crash 的主要堆棧如下:
...28 UIKit0x0000000190513360 UIApplicationMain +208
29 Qzone0x0000000101380570 main (main.m:181)30 libdyld.dylib0x00000001895205b8 _dyld_process_info_notify_release +36
Completion handler passed to -[QZWebController webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:] was not called
主要是JS調用window.alert()函數(shù)引起的酗失,從 crash 堆椧宥ぃ可以看出是 WKWebView 回調函數(shù):
+ (void) presentAlertOnController:(nonnull UIViewController*)parentController title:(nullable NSString*)title message:(nullable NSString *)message handler:(nonnullvoid(^)())completionHandler;
completionHandler 沒有被調用導致的。在適配 WKWebView 的時候规肴,我們需要自己實現(xiàn)該回調函數(shù)捶闸,window.alert()才能調起 alert 框,我們最初的實現(xiàn)是這樣的:
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {? ? UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];? ? [alertController addAction:[UIAlertAction actionWithTitle:@"確認" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { completionHandler(); }]];
[self presentViewController:alertController animated:YES completion:^{}];
}
如果 WKWebView 退出的時候拖刃,JS剛好執(zhí)行了window.alert(), alert 框可能彈不出來删壮,completionHandler 最后沒有被執(zhí)行,導致 crash兑牡;另一種情況是在 WKWebView 一打開央碟,JS就執(zhí)行window.alert(),這個時候由于 WKWebView 所在的 UIViewController 出現(xiàn)(push或present)的動畫尚未結束均函,alert 框可能彈不出來亿虽,completionHandler 最后沒有被執(zhí)行菱涤,導致 crash。我們最終的實現(xiàn)大致是這樣的:
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {if (/*UIViewController of WKWebView has finish push or present animation*/) {? ? ? ? completionHandler();return;? ? }? ? UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];? ? [alertController addAction:[UIAlertAction actionWithTitle:@"確認" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { completionHandler(); }]];if (/*UIViewController of WKWebView is visible*/)? ? ? ? [self presentViewController:alertController animated:YES completion:^{}];elsecompletionHandler();
}
確保上面兩種情況下 completionHandler 都能被執(zhí)行洛勉,消除了 WKWebView 下彈 alert 框的 crash粘秆,WKWebView 下彈 confirm 框的 crash 的原因與解決方式與 alert 類似。
另一個 crash 發(fā)生在 WKWebView 退出前調用:
-[WKWebView evaluateJavaScript: completionHandler:]
執(zhí)行JS代碼的情況下收毫。WKWebView 退出并被釋放后導致completionHandler變成野指針攻走,而此時 javaScript Core 還在執(zhí)行JS代碼,待 javaScript Core 執(zhí)行完畢后會調用completionHandler()此再,導致 crash昔搂。這個 crash 只發(fā)生在 iOS 8 系統(tǒng)上,參考Apple Open Source输拇,在iOS9及以后系統(tǒng)蘋果已經修復了這個bug巩趁,主要是對completionHandler block做了copy(refer:https://trac.webkit.org/changeset/179160);對于iOS 8系統(tǒng)淳附,可以通過在 completionHandler 里 retain WKWebView 防止 completionHandler 被過早釋放。我們最后用 methodSwizzle hook 了這個系統(tǒng)方法:
+ (void) load {? ? ? [self jr_swizzleMethod:NSSelectorFromString(@"evaluateJavaScript:completionHandler:") withMethod:@selector(altEvaluateJavaScript:completionHandler:) error:nil]; }/*? * fix: WKWebView crashes on deallocation if it has pending JavaScript evaluation? */
- (void)altEvaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler {? ? id strongSelf = self;? ? [self altEvaluateJavaScript:javaScriptString completionHandler:^(id r, NSError *e) {? ? ? ? [strongSelf title];if (completionHandler) {
completionHandler(r, e);
}
}];
}
8蠢古、其它問題
8.1奴曙、視頻自動播放
WKWebView 需要通過WKWebViewConfiguration.mediaPlaybackRequiresUserAction設置是否允許自動播放,但一定要在 WKWebView 初始化之前設置草讶,在 WKWebView 初始化之后設置無效洽糟。
8.2、goBack API問題
WKWebView 上調用 -[WKWebView goBack], 回退到上一個頁面后不會觸發(fā)window.onload()函數(shù)堕战、不會執(zhí)行JS坤溃。
8.3、頁面滾動速率
WKWebView 需要通過scrollView delegate調整滾動速率:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
}
9嘱丢、結語
本文總結了在 WKWebView 上踩過的一些坑薪介。雖然 WKWebView 坑比較多,但是相對 UIWebView 在內存消耗越驻、穩(wěn)定性方面還是有很大的優(yōu)勢汁政。盡管蘋果對 WKWebView 的開發(fā)進度過于緩慢,但相信 WKWebView 才是未來缀旁。
轉載鏈接:騰訊Bugly