WebViewJavascriptBridge是一个第三方开源框架,用于实现原生和JS交互,使用起来非常方便。下面我们一起来学习一下吧。
首先我们导入框架到项目中,采用CocoaPods或者手动导入都可以,我下面使用的是手动导入的方式。
-
导入框架
image.png
-
引入头文件
image.png -
初始化
@interface ViewController ()
@property (nonatomic, strong) WebViewJavascriptBridge *bridge;
@end
- (void)viewDidLoad {
[super viewDidLoad];
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webView];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:@"客户端调用JS方法:testJavascriptHandler" forState:UIControlStateNormal];
btn.titleLabel.font = [UIFont systemFontOfSize:12];
btn.backgroundColor = [UIColor redColor];
[btn sizeToFit];
btn.center = self.view.center;
[btn addTarget:self action:@selector(tapAction:) forControlEvents:UIControlEventTouchUpInside];
[webView addSubview:btn];
[WebViewJavascriptBridge enableLogging]; //开启日志打印
self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView]; //绑定webView
[self.bridge setWebViewDelegate:self]; //设置webView代理
/**
客户端注册方法给JS调用
*/
[_bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"JS传来的数据: %@", data);
responseCallback(@{ @"foo":@"我是客户端来的数据😆" });
}];
NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"test.html" ofType:@""];
NSURL *url = [NSURL fileURLWithPath:htmlPath];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
}
- (void)tapAction:(UIButton *)sender {
/**
客户端调用JS注册的方法: testJavascriptHandler
*/
[_bridge callHandler:@"testJavascriptHandler" data:@{ @"foo":@"before ready" }];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
4.让我们看一下运行效果
效果.gif
5.好了,大致的用法我们就说到这里。有需要的可以下载Demo查看
网友评论