WebViewJavascriptBridge(OC部分)
WebViewJavascriptBridge框架定义了两种OC和JS之间通信的方式:一种是send,发送一条消息;另一种是通过一个key调用callHandler,携带参数data,可以在responseCallback获取返回值。
-(void)initJsBridge{
if (_bridge) { return; }
UIWebView* webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webView];
// 开启日志
[WebViewJavascriptBridge enableLogging];
// 初始化连接,并且接收js通过send方法给oc发送的数据data,然后通过responseCallback给js一个返回信息(js给oc传值)
_bridge = [WebViewJavascriptBridge bridgeForWebView:webView webViewDelegate:self handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"ObjC received message from JS: %@", data);
responseCallback(@"Response for message from ObjC");
}];
// js调oc方法(可以通过data给oc方法传值,使用responseCallback将值再返回给js)
[_bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"testObjcCallback called: %@", data);
responseCallback(@"Response from testObjcCallback"); }];
// oc调js方法(通过data可以传值,通过response可以接受js那边的返回值
[_bridge callHandler:@"testJavascriptHandler" data:@{ @"foo":@"before ready" }];
//oc给js传值(通过 response接受返回值 )
[_bridge send:@"A string sent from ObjC before Webview has loaded." responseCallback:^(id responseData) {
NSLog(@"objc got response! %@", responseData);
}];
//oc给js传值(基本数据)
[_bridge send:[NSDictionary dictionaryWithObject:@"Foo" forKey:@"Bar"]];
//oc给js传值(字符串)(无返回值)
[_bridge send:@"A string sent from ObjC after Webview has loaded."];
}