WKWebView使用過程中若干技巧和坑點(diǎn)

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去打開
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • UIWebView 之痛 開發(fā)App的過程中,常常會(huì)遇到在App內(nèi)部加載網(wǎng)頁,通常用UIWebView加載。而這個(gè)...
    Style_mao閱讀 1,481評(píng)論 1 5
  • 轉(zhuǎn)載自: http://www.itdecent.cn/p/90a90bd13aac WKWebView從入門到趟...
    F麥子閱讀 681評(píng)論 0 3
  • 轉(zhuǎn)載鏈接:騰訊Bugly 導(dǎo)語 WKWebView 是蘋果在 WWDC 2014 上推出的新一代 webView ...
    Jelly_沫閱讀 2,919評(píng)論 0 3
  • WKWebView 是蘋果在 WWDC 2014 上推出的新一代 webView 組件,用以替代 UIKit 中笨...
    Aiana閱讀 4,800評(píng)論 1 8
  • 導(dǎo)語 WKWebView 是蘋果在 WWDC 2014 上推出的新一代 webView 組件,用以替代 UIKit...
    hope7th閱讀 15,071評(píng)論 4 65

友情鏈接更多精彩內(nèi)容