WKWebView的優勢
- 性能高,穩定性好,占用的內存比較小,
- 支持JS交互
- 支持HTML5 新特性
- 可以添加進度條(然并卵,不好用,還是習慣第三方的)。
- 支持內建手勢,
- 據說高達60fps的刷新頻率(不卡)
1.Xcode新建My.html文件,自定義html內容,主要代碼如下:
(1)標簽為UI樣式(寫了簡單的JS代碼,目的用于講解交互)
(2)onClick為JS事件,當JS想給OC傳遞參數時,采用如下代碼:window.webkit.messageHandlers.<方法名>.postMessage(數據)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
< h1 style = "text-align:center;background-color: #e6b500;wdith:100px;height:40px" >歡迎來到JS世界</ h1 > < p style = "text-align:center" > < a href = "github://callName_?https://github.com/wslcmk" rel = "external nofollow" >Github主頁</ a > :截獲URL調用OC</ p > < p style = "text-align:center" > < a href = "http://192.168.0.116/monkey/iOS-URNetworking/commits/master" rel = "external nofollow" >GitLab主頁</ a > </ p > < p style = "text-align:center" > < button id = "btn1" type = "button" onclick = "jsToOcFunctionOne()" > JS調用OC->不帶參數 </ button > </ p > < p style = "text-align:center" > < button id = "btn2" type = "button" onclick = "jsToOcFunctionTwo()" > JS調用OC->帶參數 </ button > </ p > < p style = "text-align:center" > < button id = "btn3" type = "button" onclick = "showAlert()" > oc捕獲到html的彈出框 </ button > </ p > <!-- JS語法--> < script type = "text/javascript" > function jsToOcFunctionOne() { window.webkit.messageHandlers.jsToOcNoPrams.postMessage({}); } function jsToOcFunctionTwo() { window.webkit.messageHandlers.jsToOcWithPrams.postMessage({"params":"我是JS參數"}); } function showAlert() { alert("我來自JS世界,被你發現了"); } //改變背景色 function changeBgColor() { document.body.style.backgroundColor = randomColor(); } |
2.KVO實現加載進度條以及標題
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
// KVO監聽:獲取進度并顯示 獲取標題并顯示 [self.webView addObserver:self forKeyPath:@ "estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; [self.webView addObserver:self forKeyPath:@ "title" options:NSKeyValueObservingOptionNew context:nil]; #pragma mark - KVO - ( void )observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:( void *)context { if ([keyPath isEqualToString:@ "title" ]&&object == _webView) { self.title = _webView.title; } else if ([keyPath isEqualToString:@ "estimatedProgress" ] && object == _webView) { self.progressView.progress = _webView.estimatedProgress; if (_webView.estimatedProgress >= 1.0f) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.progressView.progress = 0; }); } } } |
3.通過攔截url方式,JS調用OC代碼,決定是否跳轉(WKNavigationDelegate代理)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#pragma mark -- WKNavigationDelegate WKNavigationDelegate主要處理一些跳轉、加載處理操作 // 根據WebView對于即將跳轉的HTTP請求頭信息和相關信息來決定是否跳轉 - ( void )webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:( void (^)(WKNavigationActionPolicy))decisionHandler { NSString * urlStr = navigationAction.request.URL.absoluteString; NSLog(@ "發送跳轉請求:%@" ,urlStr); //自己定義的協議頭 NSString *htmlHeadString = @ "github://" ; if ([urlStr hasPrefix:htmlHeadString]){ UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@ "通過截取URL調用OC" message:@ "前往Github?" preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:([UIAlertAction actionWithTitle:@ "取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { }])]; [alertController addAction:([UIAlertAction actionWithTitle:@ "打開" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { NSURL * url = [NSURL URLWithString:[urlStr stringByReplacingOccurrencesOfString:@ "github://callName_?" withString:@ "" ]]; [[UIApplication sharedApplication]canOpenURL:url]; }])]; [self presentViewController:alertController animated:YES completion:nil]; decisionHandler(WKNavigationActionPolicyCancel); } else { decisionHandler(WKNavigationActionPolicyAllow); } } |
4.OC獲取JS alert內容(WKUIDelegate處理警告、輸入、以及確認,這里只列舉了alert。輸入和確認就不一一列舉了,分別是JS端confirm和prompt函數觸發)
當調用JS端alert函數時:通過如下代理獲取alert內容
1
2
3
4
5
6
7
8
|
#pragma mark -- WKUIDelegate WKUIDelegate主要處理JS腳本,確認框,警告框等 - ( void )webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:( void (^)( void ))completionHandler { UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@ "JS-alert-Action" message:message?:@ "" preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:([UIAlertAction actionWithTitle:@ "OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { completionHandler(); }])]; [self presentViewController:alertController animated:YES completion:nil]; } |
5.OC調用JS代碼,實現改變JS頁面顏色(通過evaluateJavaScript函數、jsString為JS端方法名)
1
2
3
4
5
6
7
8
9
|
#pragma mark -navigationItem Action - ( void )ocToJs { // changeColor()是JS方法名 NSString *jsString = [NSString stringWithFormat:@ "changeBgColor()" ]; [_webView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) { }]; } |
6.通過接受JS方法名捕捉方法(帶參數和不帶參數,JS端向IOS傳遞參數,采用window.webkit.messageHandlers.<方法名>.postMessage(數據))
(1)需要引入WKUserContentController、主要代碼如下
1
2
3
4
5
6
7
|
//創建網頁配置對象 WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; WKUserContentController * wkUController = [[WKUserContentController alloc] init]; //注冊一個name為jsToOcNoPrams的js方法 設置處理接收JS方法的對象 [wkUController addScriptMessageHandler:self name:@ "jsToOcNoPrams" ]; [wkUController addScriptMessageHandler:self name:@ "jsToOcWithPrams" ]; config.userContentController = wkUController; |
(2)核心代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#pragma mark - 通過接收JS傳出消息的name進行捕捉的回調方法 - ( void )userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{ NSLog(@ "name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n" ,message.name,message.body,message.frameInfo); //用message.body獲得JS傳出的參數體 NSDictionary * parameter = message.body; //JS調用OC if ([message.name isEqualToString:@ "jsToOcNoPrams" ]){ UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@ "js調用到了oc" message:@ "不帶參數" preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:([UIAlertAction actionWithTitle:@ "OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }])]; [self presentViewController:alertController animated:YES completion:nil]; } else if ([message.name isEqualToString:@ "jsToOcWithPrams" ]){ UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@ "js調用到了oc" message:parameter[@ "params" ] preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:([UIAlertAction actionWithTitle:@ "OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }])]; [self presentViewController:alertController animated:YES completion:nil]; } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://juejin.im/post/5c4e60b95188252449234a13