WKWebView
iOS8以后,蘋果新增加了WebKit框架了,提供了WKWebView這個(gè)全新的瀏覽器控件。對(duì)比UIWebView,最直觀的感受就是程序占用內(nèi)存大幅度降低了,加載速度快了,內(nèi)存泄漏問題也解決了。
WKWebView使用技巧
WKWebView緩存相關(guān)
如果想及時(shí)的清理WKWebView產(chǎn)生的緩存,可以使用以下方法:
iOS9及之后的:
NSSet *websiteDataTypes
= [NSSet setWithArray:@[
WKWebsiteDataTypeDiskCache,
WKWebsiteDataTypeMemoryCache,
]];
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
//// Execute
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
// Done
}];
iOS8:
NSString *cachePath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingString:@"/Cookies"];
[[NSFileManager defaultManager] removeItemAtPath:cachePath error:nil];
自定義WKWebView的User-Agent:
NSString *newAgent = [oldAgent stringByAppendingString:@"***"];
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent" : newAgent}];
或者
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:@"***" forHTTPHeaderField:@"User-Agent"];
[self.webView loadRequest:request];
WKWebView與JS的交互
如果是簡單的接受JS的通知信息,可以實(shí)現(xiàn)WKUIDelegate的其中一些方法:
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler;
當(dāng)JS調(diào)用alert、panel、prompt方法時(shí),如果實(shí)現(xiàn)了以上的方法則調(diào)用以上方法。
如果是自定義可供JS調(diào)用方法的對(duì)象,則應(yīng)該在WKWebView初始化過程中注入實(shí)現(xiàn)了WKScriptMessageHandler協(xié)議的交互對(duì)象:
WKUserContentController *userContentController = [WKUserContentController new];
[userContentController addScriptMessageHandler:[MyJSHandler new] name:@"MyJSHandler"];
// Create the configuration with the user content controller
WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
configuration.userContentController = userContentController;
_shareWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
JS方調(diào)用交互對(duì)象方法如下:
var messsage="test";
if(window.MyJSHandler) {
window.MyJSHandler.postMessage(message);
} else {
window.webkit.messageHandler.MyJSHandler.postMessage(message);
}
動(dòng)態(tài)獲取WKWebView可滾動(dòng)區(qū)域的大小
對(duì)WKWebView的scrollSize進(jìn)行KVO就可以動(dòng)態(tài)獲取其滾動(dòng)區(qū)域大小
[_shareWebView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if (object == _shareWebView.scrollView && [keyPath isEqual:@"contentSize"]) {
UIScrollView *scrollView = _shareWebView.scrollView;
CGRect rect = _shareWebView.frame;
JZLog(@"web view height : %f",scrollView.contentSize.height);
}
}
禁止WKWebView的長按呼出菜單
在WKWebView的初始化過程中注入JS代碼
NSString *source = @"var style = document.createElement('style'); \
style.type = 'text/css'; \
style.innerText = '*:not(input):not(textarea) { -webkit-user-select: none; -webkit-touch-callout: none; }'; \
var head = document.getElementsByTagName('head')[0];\
head.appendChild(style);";
WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
// Create the user content controller and add the script to it
WKUserContentController *userContentController = [WKUserContentController new];
[userContentController addUserScript:script];
// Create the configuration with the user content controller
WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
configuration.userContentController = userContentController;
_shareWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
禁止WKWebView的捏合手勢放大縮小
實(shí)現(xiàn)WKNavigationDelegate中的以下方法并執(zhí)行JS代碼
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
// 禁止放大縮小
NSString *injectionJSString = @"var script = document.createElement('meta');"
"script.name = 'viewport';"
"script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
"document.getElementsByTagName('head')[0].appendChild(script);";
[webView evaluateJavaScript:injectionJSString completionHandler:nil];
}
WKWebView使用過程中要注意的坑點(diǎn)
Cookie相關(guān)
WKWebView 的存儲(chǔ)體系與 UIWebVIew 完全不一樣,只能手動(dòng)給它添加 Cookie。
//自己設(shè)定請(qǐng)求的Cookie值
[request setValue:myCookie forHTTPHeaderField:@"Cookies"];
//或者在WKWebView初始化時(shí)候注入JS代碼
NSString *source = [NSString stringWithFormat:@"ocument.cookies=%@",myCookie];
WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
// Create the user content controller and add the script to it
WKUserContentController *userContentController = [WKUserContentController new];
[userContentController addUserScript:script];
// Create the configuration with the user content controller
WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
configuration.userContentController = userContentController;
_shareWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
WKWekView的請(qǐng)求不會(huì)被NSURLProtocol所攔截
已經(jīng)確認(rèn)到iOS10.2為止 WKWebView都不支持NSURLProtocol
本地HTML資源加載相關(guān)
iOS8:
先將本地 HTML 文件的數(shù)據(jù) copy 到 tmp /www目錄中,然后再使用 loadRequest 來加載。但是如果在 HTML 中加入了其他資源文件,例如 js,css,image 等也必須一同 copy 到 tmp /www目錄 中。
iOS9及以后:
使用以下API進(jìn)行加載
[WKWebView loadFileURL:allowingReadAccessToURL:]```
#跨域問題
WebKit框架對(duì)跨域進(jìn)行了安全性檢查限制,不允許跨域,比如從一個(gè) HTTP 頁對(duì) HTTPS 發(fā)起請(qǐng)求是無效的。而系統(tǒng)的 Safari ,iOS 10出現(xiàn)的 SFSafariViewController 都是支持跨域的。
所以解決方法是實(shí)現(xiàn)WKNavigationDelegate中的
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;```
方法,在里面進(jìn)行域名的判斷,需要跨域的時(shí)候用SFSafariViewController去打開