iOS/Android与前端Vue的交互

1,398 阅读1分钟

这阵子移动端两个端都和前端做了交互 记录一下

前端调用iOS/Android(以目前前端最流行的框架Vue为例 )

//判断安卓
const isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Linux') > -1;
//判断iOS
const isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
if (isAndroid) {
  // 'scan'为标志符 app定义   ,data 为传过去app的值
   window.WebViewJavascriptBridge.callHandler( 'scan', data
   function(responseData) {});
}else if (isIOS) {
    //ios如果不需要传值 则data要传null
   window.webkit.messageHandlers.scan.postMessage(data)
}

iOS注册接受前端的事件 (目前基本上都是WKWebview,以此为例)

WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
self.userController = [[WKUserContentController alloc] init];
[self.userController addScriptMessageHandler:self name:@"scan"];
//在代理方法里
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
 if([message.name isEqualToString:@"scan"]){ //调用 }
}

安卓注册接受前端的事件 ( 借助jsbridge轻松实现 )

onScan(mWebView);
private void onScan(BridgeWebView webView) {
   webView.registerHandler("scan", (data, function) -> {
        
   });
}

==============

移动端调用前端的方法(需要注意的是如果h5是用js写的方法则h5端不需要做什么操作,如果h5是vue实现的话需要把方法暴露出来)

 //这是写在methods中给app调用方法
 scanResult(resultStr){
      console.log('app传过来的数据',resultStr)
 },
 //此外需要在mounted里暴露这个方法
 mounted(){ 
    window.scanResult = this.scanResult;
},

iOS调用h5的方法

NSString *anyId = @"";  (传递的参数)
NSString *jsStr  = [NSString stringWithFormat:@"scanResult('%@')",anyId];
[self.myWebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
   if (error) {
       NSLog(@"调用错误");
    }
}];

安卓调用h5的方法

String deviced = data.getStringExtra("result")   (传递的参数)
mWebView.loadUrl("javascript:scanResult('" + deviced + "')");

后续 这样基本上都能完成三端的交互啦 (^o^)/~