簡單說說iOS之WKWebView的用法

小科科發表於2019-01-28

1.Xcode新建My.html檔案,自定義html內容,主要程式碼如下:

(1)標籤為UI樣式(寫了簡單的JS程式碼,目的用於講解互動)

(2)onClick為JS事件,當JS想給OC傳遞引數時,採用如下程式碼:window.webkit.messageHandlers.<
方法名>
.postMessage(資料)

<
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">
Github主頁<
/a>
:截獲URL呼叫OC<
/p>
<
p style="text-align:center">
<
a href="http://192.168.0.116/monkey/iOS-URNetworking/commits/master">
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實現載入進度條以及標題

//    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代理)

#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內容

#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端方法名)

#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、主要程式碼如下

//建立網頁配置物件        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)核心程式碼

#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#comment

相關文章