使用WKWebView的時候,若是想要實現JS調用OC方法,除了攔截URL以外,還有一種簡單的方式。那就是利用WKWebView的新特性MessageHandler來實現JS調用原生方法。
window.webkit.messageHandlers.<name>.postMessage(<messageBody>) //其中<name>,就是上面方法裏的第二個參數`name`。 //例如咱們調用API的時候第二個參數填@"Share",那麼在JS裏就是: //window.webkit.messageHandlers.Share.postMessage(<messageBody>) //<messageBody>是一個鍵值對,鍵是body,值能夠有多種類型的參數。 // 在`WKScriptMessageHandler`協議中,咱們能夠看到mssage是`WKScriptMessage`類型,有一個屬性叫body。 // 而註釋裏寫明瞭body 的類型: Allowed types are NSNumber, NSString, NSDate, NSArray, NSDictionary, and NSNull.
WKWebViewConfiguration
對象,配置各個API對應的MessageHandler。WKUserContentController
對象能夠添加多個scriptMessageHandler。html
看了示例代碼,會很容易理解。示例代碼以下:java
// 這是建立configuration 的過程 WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; WKPreferences *preferences = [WKPreferences new]; preferences.javaScriptCanOpenWindowsAutomatically = YES; preferences.minimumFontSize = 40.0; configuration.preferences = preferences; - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; // addScriptMessageHandler 很容易致使循環引用 // 控制器 強引用了WKWebView,WKWebView copy(強引用了)configuration, configuration copy (強引用了)userContentController // userContentController 強引用了 self (控制器) [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"ScanAction"]; [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Location"]; [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Share"]; [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Color"]; [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Pay"]; [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Shake"]; [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"GoBack"]; [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"PlaySound"]; }
須要注意的是addScriptMessageHandler
很容易引發循環引用,致使控制器沒法被釋放,因此須要加入如下這段:git
- (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; // 所以這裏要記得移除handlers [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"ScanAction"]; [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Location"]; [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Share"]; [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Color"]; [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Pay"]; [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Shake"]; [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"GoBack"]; [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"PlaySound"]; }
直接看示例代碼吧:github
self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration]; NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil]; NSURL *fileURL = [NSURL fileURLWithPath:urlStr]; [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL]; self.webView.navigationDelegate = self; self.webView.UIDelegate = self; [self.view addSubview:self.webView];
#pragma mark - WKScriptMessageHandler - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { // message.body -- Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull. if ([message.name isEqualToString:@"ScanAction"]) { NSLog(@"掃一掃"); } else if ([message.name isEqualToString:@"Location"]) { [self getLocation]; } else if ([message.name isEqualToString:@"Share"]) { [self shareWithParams:message.body]; } else if ([message.name isEqualToString:@"Color"]) { [self changeBGColor:message.body]; } else if ([message.name isEqualToString:@"Pay"]) { [self payWithParams:message.body]; } else if ([message.name isEqualToString:@"Shake"]) { [self shakeAction]; } else if ([message.name isEqualToString:@"GoBack"]) { [self goBack]; } else if ([message.name isEqualToString:@"PlaySound"]) { [self playSound:message.body]; } }
message.boby 就是JS 裏傳過來的參數。咱們不一樣的方法先作一下容錯性判斷。而後正常取值就能夠了。web
HMTL的源碼跟以前的HTML內容差很少,只有JS的調用部分改變了。數組
// 傳null function scanClick() { window.webkit.messageHandlers.ScanAction.postMessage(null); } // 傳字典 function shareClick() { window.webkit.messageHandlers.Share.postMessage({title:'測試分享的標題',content:'測試分享的內容',url:'http://www.baidu.com'}); } // 傳字符串 function playSound() { window.webkit.messageHandlers.PlaySound.postMessage('shake_sound_male.wav'); } // 傳數組 function colorClick() { window.webkit.messageHandlers.Color.postMessage([67,205,128,0.5]); }
這裏使用WKWebView 實現OC 調用JS方法跟上一篇是同樣的,仍是利用- evaluateJavaScript:completionHandler:
。像下面這樣使用:app
// 將分享結果返回給js NSString *jsStr = [NSString stringWithFormat:@"shareResult('%@','%@','%@')",title,content,url]; [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) { NSLog(@"%@----%@",result, error); }];
loadURL("firstClick://shareClick?title=分享的標題&content=分享的內容&url=連接地址&imagePath=圖片地址"); }
將上面的url 放入連接地址這裏後,根本沒法區分share_uuid是其餘參數,仍是url裏附帶的參數。
可是使用MessageHandler 就能夠避免特殊字符引發的問題。dom