三层通信模型:
应用层、解释层、会话层;
通信协议:
通信原语;
报文格式;
网络层:
_evaluateJavascript
会话层:
#define kQueueHasMessage @"__wvjb_queue_message__"
#define kBridgeLoaded @"__bridge_loaded__"
表示层:
NSString* responseId = message[@"responseId"];
WVJBResponseCallback responseCallback = _responseCallbacks[responseId];
应用层:
[_bridge callHandler:@"testJavascriptHandler" data:data responseCallback:^(id response) {
NSLog(@"testJavascriptHandler responded: %@", response);
}];
通信机制:
1、js发送消息
sendMessageQueue.push(message);
messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
2、oc端接收消息
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
NSString *messageQueueString = [self _evaluateJavascript:[_base webViewJavascriptFetchQueyCommand]];
[_base flushMessageQueue:messageQueueString];
3、oc端消息处理:
WVJBHandler handler = self.messageHandlers[message[@"handlerName"]];
handler(message[@"data"], responseCallback);
构建返回报文并返回:
NSString* callbackId = message[@"callbackId"];
if (callbackId) {
responseCallback = ^(id responseData) {
if (responseData == nil) {
responseData = [NSNull null];
}
WVJBMessage* msg = @{ @"responseId":callbackId, @"responseData":responseData };
[self _queueMessage:msg];
};
}
4、oc端发送消息
NSString* javascriptCommand = [NSString stringWithFormat:@"WebViewJavascriptBridge._handleMessageFromObjC('%@');", messageJSON];
[self _evaluateJavascript:javascriptCommand];
通信原语:通信控制
#define kOldProtocolScheme @"wvjbscheme"
#define kNewProtocolScheme @"https"
#define kQueueHasMessage @"__wvjb_queue_message__"
#define kBridgeLoaded @"__bridge_loaded__"
https://__bridge_loaded__/
https://__wvjb_queue_message__/
通信报文:
{
callbackId = "cb_1_1560136340114";
data = {
foo = bar;
};
handlerName = testObjcCallback;
}
会话维护:
callbackId
responseId
应用协议:
handlerName
生命周期管理
https://__bridge_loaded__/