WkWebView是IOS8中引入的新組件,蘋果將UIWebViewDelegate 與 UIWebView 重構(gòu)成了 14 個(gè)類和 3 個(gè)協(xié)議并引入了不少新的功能和接口。由于一直以來蘋果對于WebView內(nèi)核封鎖的程度是令人發(fā)指的,WkWebView的引入無疑是另廣大開發(fā)者興奮的事。
與傳統(tǒng)UIWebView的優(yōu)劣對比
優(yōu)點(diǎn):? A.大幅降低網(wǎng)頁加載時(shí)所占用的內(nèi)存
? ? ? ? ?B.大幅增加網(wǎng)頁加載速度
? ? ? ? ?C.支持高達(dá) 60 fps 的滾動(dòng)刷新率,內(nèi)置了手勢探測
? ? ? ? ?D.提供更多Web新功能和接口
? ? ? ? ?E.支持了更多的HTML5特性
? ? ? ? ?F.更優(yōu)雅的與JS的交互方式
缺點(diǎn):A.WkWebView不再支持頁面緩存
? ? ? ? ?B.WkWebView不可以實(shí)現(xiàn)NSURLProtocol 攔截
看到它相比于UIWebView有著那么多的優(yōu)點(diǎn),是不是已經(jīng)心動(dòng)了呢?那么接下來與筆者一起走入WkWebView的奇妙世界吧~
新增的屬性
1.estimatedProgress
以往WebView的加載進(jìn)度條的具體進(jìn)度值都是假的數(shù)據(jù),而estimatedProgress則可以用來顯示真實(shí)的進(jìn)度值變化。estimatedProgress是通過KVO的監(jiān)控來進(jìn)行使用的。
[webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"estimatedProgress"]) {
if (object == webView) {
double progress = webView.estimatedProgress
/** 用當(dāng)前獲取的進(jìn)度值去處理進(jìn)度條控件 */
}
else{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
}
2.title
與estimatedProgress的使用方式類似,可以獲取到html頁面<title>標(biāo)簽下設(shè)置的值
[webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"title"]) {
if (object == webView) {
NSString *title = webView.title;
}
else{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
}
3.WKWebViewConfiguration
WKWebViewConfiguration可以設(shè)置偏好設(shè)置,與網(wǎng)頁交互的配置,注入對象,注入js等
WKWebViewConfiguration *config =[[WKWebViewConfiguration alloc]init];
/** WebView的偏好設(shè)置 */
config.preferences.minimumFontSize = 10;
config.preferences.javaScriptEnabled = YES;
/** 默認(rèn)是不能通過JS自動(dòng)打開窗口的,必須通過用戶交互才能打開 */
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
/** ?添加JS到到HTML中 ?*/
NSString *js = @"window.alert('歡迎體驗(yàn)WkWebView!!');";
WKUserScript *script = [[WKUserScript alloc]initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKWebViewConfiguration *config =[[WKWebViewConfiguration alloc]init];
[config.userContentController addUserScript:script];
/** 用WkWebView的 - (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration 方法初始化webView */
webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:config];
新的代理方法
WkWebView中提供了新的三種代理方法,分別是WKNavigationDelegate、WKUIDelegate、WKScriptMessageHandler,下文將對其作用的場景進(jìn)行一一介紹。
1.WKNavigationDelegate
該代理方法主要是用來追蹤webview的加載過程,和傳統(tǒng)的UIWebView比較相似,分別對頁面開始加載、加載完成、加載失敗等幾個(gè)過程進(jìn)行事件捕捉和追蹤,另外在頁面的跳轉(zhuǎn)時(shí)也可對其進(jìn)行攔截處理、如過濾某些特定網(wǎng)頁等業(yè)務(wù)操作。
/** 頁面開始加載時(shí)調(diào)用 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
/** 當(dāng)內(nèi)容開始返回時(shí)調(diào)用 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;
/** 頁面加載完成之后調(diào)用 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
/** 頁面加載失敗時(shí)調(diào)用 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;
/*** 以上4個(gè)代理委托是不是很眼熟?沒錯(cuò),其實(shí)就是對應(yīng)UIWebView中的那幾個(gè)代理方法 ***/
/** 接收到服務(wù)器跳轉(zhuǎn)請求之后調(diào)用 */
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation;
/** 在收到響應(yīng)后,決定是否跳轉(zhuǎn) */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
// 如果響應(yīng)的地址是百度,則允許跳轉(zhuǎn)
if ([navigationResponse.response.URL.host.lowercaseString isEqual:@"www.baidu.com"]) {
decisionHandler(WKNavigationResponsePolicyAllow);
return;
}
//否則不允許跳轉(zhuǎn)
decisionHandler(WKNavigationResponsePolicyCancel);
}
/** 在發(fā)送請求之前,決定是否跳轉(zhuǎn) */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
// 如果響應(yīng)的地址是百度,則允許跳轉(zhuǎn)
if ([navigationResponse.response.URL.host.lowercaseString isEqual:@"www.baidu.com"]) {
decisionHandler(WKNavigationResponsePolicyAllow);
return;
}
//否則不允許跳轉(zhuǎn)
decisionHandler(WKNavigationResponsePolicyCancel);
}
2.WKUIDelegate
這個(gè)代理中包含3個(gè)針對于web界面的三種提示框(警告框、確認(rèn)框、輸入框)的彈出事件捕捉
/** ?確認(rèn)框 */
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
[[[UIAlertView alloc] initWithTitle:@"標(biāo)題" message:message delegate:nil cancelButtonTitle:@"確認(rèn)" otherButtonTitles: nil] show];
completionHandler();
}
/**? 警告框 */
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler;
/** ?輸入框 */
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler;
/** webview關(guān)閉事件 */
- (void)webViewDidClose:(WKWebView *)webView;
3.WKScriptMessageHandler
這個(gè)協(xié)議只有一個(gè)方法,它是APP與Web進(jìn)行交互的關(guān)鍵,在從web中接收到一個(gè)腳本時(shí)調(diào)用,在下文中會(huì)詳細(xì)進(jìn)行說明。
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;
更優(yōu)雅的與Web交互
在講WKWebView之前,讓我們先來看一下UIWebView是如何與Web進(jìn)行交互的。
UIWebView -- APP 調(diào) Web
NSString * result = [webView stringByEvaluatingJavaScriptFromString:@"func()"];
ios9默認(rèn)是不允許加載http請求的,對于webview加載http網(wǎng)頁也是不允許的。可以通過修改info.plist取消http限制。
UIWebView -- Web 調(diào) APP
1.在APP本地先寫一個(gè)方法如下:
-(void)callNativeFun:(NSString *)args {
}
2.在UIWebView的delegate方法中注入一段JS源碼
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *js = @"(function() {\
window.JSBridge = {};\
window.JSBridge.callFunction = function(functionName, args){\
var url = \"hybrid://invoke?\";\
var callInfo = {};\
callInfo.functionname = functionName;\
if (args)\
{\
callInfo.args = args;\
}\
url += JSON.stringify(callInfo);\
var rootElm = document.documentElement;\
var iFrame = document.createElement(\"IFRAME\");\
iFrame.setAttribute(\"src\",url);\
rootElm.appendChild(iFrame);\
iFrame.parentNode.removeChild(iFrame);\
};\
return true;\
})();";
[webView stringByEvaluatingJavaScriptFromString:js];
3.在Html某個(gè)事件中調(diào)用如下方法
window.JSBridge.callFunction("callNative", "so many args");
當(dāng)html調(diào)用這段注入的JS方法后,會(huì)將hybrid://invoke? 以及后面拼接的內(nèi)容以IFrame的方式進(jìn)行加載,在加載的同時(shí)會(huì)出發(fā)APP的delegate方法
4.在APP的delegate中實(shí)現(xiàn)對本地方法的調(diào)用,從而完成Web到App的調(diào)用
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString *urlStr = [NSString stringWithString:url];
if ([[urlStr lowercaseString] hasPrefix:@“hybrid://invoke?”]){
urlStr = [urlStr substringFromIndex:protocolPrefix.length];
urlStr = [urlStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *callInfo = [NSJSONSerialization JSONObjectWithData:[urlStr dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
NSString *functionName = [callInfo objectForKey:@"functionname"];
NSString * args = [callInfo objectForKey:@"args"];
if ([functionName isEqualToString:@"callNative"]) {
/** ?在此處完成對預(yù)先定義好的native方法進(jìn)行調(diào)用 */
[self callNativeFun:args];
}
return NO;
}
return YES;
}
如上代碼所述,UIWebView是通過Html的iframe來制造頁面刷新再解析自定義協(xié)議,這種做法其實(shí)是比較lower的,也是對于蘋果對UIWebView內(nèi)核封閉的無奈。而WKWebView則是可以直接使用已經(jīng)事先注入的js代碼,runtime的將js接口給 Native 層傳值。
WKWebView -- APP 調(diào) Web
NSString *js = @"window.alert('歡迎體驗(yàn)WkWebView!!');";
[webView evaluateJavaScript:js completionHandler:nil];
WKWebView -- Web 調(diào) APP
1.在webview初始化之前先注冊一個(gè)名為hybridDemo的handler對象。
WKWebViewConfiguration *config =[[WKWebViewConfiguration alloc]init];
[config.userContentController addScriptMessageHandler:self name:@"hybridDemo"];
webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:config];
2.在html端調(diào)用JS來訪問之前注冊的handler對象,并通過調(diào)用postMessage方法把數(shù)據(jù)傳到app。
var message = {"method":"hello","args":"let go"};
window.webkit.messageHandlers.webViewApp.postMessage(message);
3.在webview容器中實(shí)現(xiàn)上文提過的WKScriptMessageHandler委托,從而響應(yīng)來自于JS端下發(fā)的message。
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSDictionary *dic = message.body;
NSString *method = [dic objectForKey:@"method"];
NSString *param = [dic objectForKey:@"args"];
/** ?doSomeThing..... */
}