越來(lái)越多的項(xiàng)目中使用Native和網(wǎng)頁(yè)的混合開發(fā)弃舒,這使得純客戶端工作大大減輕痰娱。隨著手機(jī)硬件的提升牍疏,軟件卡頓問(wèn)題也會(huì)越來(lái)越小杖剪。之前做web端交互的時(shí)候冻押,用的WebViewJavascriptBridge的庫(kù),這個(gè)庫(kù)十分強(qiáng)大摘盆,只是oc端和web端定好function的名稱翼雀,就可以互通消息,但本篇只記錄WKWebView原生代碼交互孩擂,如果有錯(cuò)誤狼渊,還請(qǐng)指教。
- 加載本地html
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.preferences.minimumFontSize = 18;
self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height/2) configuration:config];
[self.view addSubview:self.wkWebView];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSURL *baseURL = [[NSBundle mainBundle] bundleURL];
[self.wkWebView loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:baseURL];
- OC端接收來(lái)著JS端發(fā)送的消息
WKUserContentController,遵守@protocol WKScriptMessageHandler協(xié)議
// config.userContentController 點(diǎn)擊去看到這屬性是: 就是把前面這個(gè)和web視圖聯(lián)系起來(lái)
WKUserContentController *userCC = config.userContentController;
//JS調(diào)用OC 添加處理腳本
/*! @abstract Adds a script message handler.
@param scriptMessageHandler The message handler to add.
@param name The name of the message handler.
@discussion Adding a scriptMessageHandler adds a function
window.webkit.messageHandlers.<name>.postMessage(<messageBody>) for all
frames.
*/
[userCC addScriptMessageHandler:self name:@"showMobile_qin"];
[userCC addScriptMessageHandler:self name:@"showName"];
[userCC addScriptMessageHandler:self name:@"showSendMsg"];
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"userScripts:%@",userContentController.userScripts);
NSLog(@"name:%@,,body:%@",message.name,message.body);
if ([message.name isEqualToString:@"showSendMsg"]) {
NSDictionary *dic = message.body;
NSString *info = [NSString stringWithFormat:@"message是:%@",dic[@"message"]];
NSLog(@"info:%@",info);
}
}
- html端
這是html互通消息端固定的格式寫法
window.webkit.messageHandlers.<name>.postMessage(<messageBody>) for all
// JS代碼 事件列表
function btnClick() {
var dic = {"message": "JS發(fā)消息給OC", "ls": "李四1" };
window.webkit.messageHandlers.showSendMsg.postMessage(dic);
}
至此类垦,js可以響應(yīng)來(lái)自客服端的事件狈邑,而oc去響應(yīng)的js端的事件更加簡(jiǎn)單。
OC代碼
[self.wkWebView evaluateJavaScript:@"alertSendMsg('OC端','呼喚')" completionHandler:^(id _Nullable other, NSError * _Nullable error) {
NSLog(@"other:%@,error:%@",other,error);
}];
- html代碼
<script>
function alertSendMsg(num,msg) {
document.getElementById('demo').innerHTML = '已接收' + num + ',' + msg + '!!'
}
</script>
OK蚤认,大概就是這樣米苹,這個(gè)demo中,沒(méi)有多么負(fù)責(zé)的功能砰琢,但是js 和oc 互通消息已經(jīng)能做到了蘸嘶。