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