混合开发的重要性不言而喻,一个移动端开发的了解前端开发是一个趋向,总之每个人都向往成为一个全栈工程师,废话不多说,直接上主题
一、交互(UIWebView)
1、OC调用JS
(1)OC调用代码
[self.webView stringByEvaluatingJavaScriptFromString:@"ocCallJSFunction({'name':'xiaoxiao'})"];
(2)JS代码
</script>
function ocCallJSFunction(data) {
var obj = eval(data);
alert(obj.name);
}
<script>
2、JS调用OC
(1)OC代码
- (void)webViewDidFinishLoad:(UIWebView *)webView {
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
context[@"jsCallOCFunction"] = ^() {
NSLog(@"JS调用OC成功");
NSArray *args = [JSContext currentArguments];
for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal.toDictionary);
}
};
}
(2)JS调用代码
</script>
var message = {
'method' : 'hello',
'param1' : 'dada',
};
jsCallOCFunction(message);
<script>
二、交互(WKWebView)
1、OC调用JS
(1)OC调用代码
[self.wkWebView evaluateJavaScript:@"ocCallJSFunction({'name':'xiaoxiao'})" completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
NSLog(@"evaluateJavaScript, obj = %@, error = %@", obj, error);
}];
(2)JS代码
</script>
function ocCallJSFunction(data) {
var obj = eval(data);
alert(obj.name);
}
<script>
2、JS调用OC
(1)OC代码
// 初始化WKWebView
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
[config.userContentController addScriptMessageHandler:self name:@"jsCallOCFunction"];
WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"name = %@",message.name);
NSLog(@"body = %@",message.body);
NSLog(@"frameInfo = %@",message.frameInfo);
}
(2)JS调用代码
</script>
var message = {
'method' : 'hello',
'param1' : 'dada',
};
window.webkit.messageHandlers.jsCallOCFunction.postMessage(message);
<script>
三、交互(WebViewJavascriptBridge)
功能总结:
OC调JS调用成功,JS可以回调数据到OC
JS调OC调用成功,OC可以回调数据到JS
1、OC调用JS
(1)OC调用代码
_bridge = [WebViewJavascriptBridge bridgeForWebView:wkWebView];
id data = @{@"name" : @"xiaoxiao"};
[_bridge callHandler:@"ocCallJSFunction" data:data responseCallback:^(id response) {
NSLog(@"这里是OC调用JS成功后,JS回调的参数:%@", response);
}];
(2)JS代码
</script>
// 注册JS方法供OC调用
bridge.registerHandler('ocCallJSFunction', function(data, responseCallback) {
var obj = eval(data);
alert(obj.userId);
var responseData = { 'code':'200' }
responseCallback(responseData)
})
<script>
2、JS调用OC
(1)OC代码
[_bridge registerHandler:@"jsCallOCFunction" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"JS传过来的参数: %@", data);
responseCallback(@"这是JS调用OC成功后,OC回调的参数");
}];
(2)JS调用代码
// JS调用OC注册的方法
bridge.callHandler('jsCallOCFunction', {'name':'dada'}, function responseCallback(responseData) {
alert(responseData);
})