1、oc调用vue方法
methods:{
hwajax:function (strings) {
this.tokenString=strings;
}
}
需要暴露方法
mounted:function () {
window.hwajax = this.hwajax;
}
// 页面加载完成之后调用在iOS里面调用js方法:
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSString *jsStr = @"hwajax('lvkaike')";
NSLog(@"%@",jsStr);
[webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable d, NSError * _Nullable error) {
NSLog(@"%@",d);
NSLog(@"%@",error);
}];
}
2、oc 调用vue方法
methods:{
onLineCollectionFun:function () {
var u = navigator.userAgent;
//android终端
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
//ios终端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
if(isAndroid){
window.android.ocOnLineCollectionFun();
}else {
console.log('在线收款')
window.webkit.messageHandlers.ocOnLineCollectionFun.postMessage({'methodsID':'1'});
}
}
}
wkwebview代理设置
#import <WebKit/WebKit.h>
@interface GuestHomeController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
@property(nonatomic,strong) WKWebView * webView;
@property(nonatomic,weak) MBProgressHUD*hud;
@end
初始化wkwebview
WKWebView*webV=[[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds configuration:configuration];
[self.view addSubview:webV];
_webView=webV;
webV.backgroundColor=[UIColor groupTableViewBackgroundColor];
webV.UIDelegate=self;
webV.navigationDelegate=self;
NSString * urlString = @"";
urlString = [kBaseWebURL stringByAppendingString:@"guesthome"];
[webV loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
第一步.我们需要在WKWebView创建的过程中初始化添加ScriptMessageHandler
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = [WKUserContentController new];
[configuration.userContentController addScriptMessageHandler:self name:@"ocOnLineCollectionFun"];
然后实现代理方法.监听JS的回调.为了查看效果,代码如下所示.
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
HWDLog(@"%@", message.body);
HWDLog(@"%@", message.name);
NSDictionary * body = [message.body objectForKey:@"body"];
if ([message.name isEqualToString:@"ocOnLineCollectionFun"]) {
[self onLineCollectController];
}
}
暴露方法,这步很重要
mounted:function () {
window.onLineCollectionFun = this.onLineCollectionFun;
}
vue里调用方法使用:
this.onLineCollectionFun()
网友评论