Back

[转载] 使用WebViewJavascriptBridge进行ios与vuejs的交互

发布时间: 2017-03-30 03:58:00

原文: http://duxiao.siwei.tech/blog/posts/webviewjavascriptbridge-ios-vuejs

杜骁(http://duxiao.siwei.tech  ) 在这方面有很好的实践。   

非常重要。 

下面是原文. 

WebViewJavascriptBridge 的github

用于测试的html的demo: testios.siwei.tech

能实现oc向js通信双向通信

1、首先将example中的oc的WebViewJavascriptBridge组件包导入项目中(pod中下载的5.0版的中貌似有什么问题,没有成功)

2、在使用的页面中引用

#import "WebViewJavascriptBridge.h"

3、定义一个方法(理解成语法糖就好)

  methods: {
setupWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
window.WVJBCallbacks = [callback];
var WVJBIframe = document.createElement('iframe');
WVJBIframe.style.display = 'none';
WVJBIframe.src = 'https://__bridge_loaded__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}
}

4、在mounted中调用上面方法的callback

this.setupWebViewJavascriptBridge(function(bridge) {
alert('test');
})

5、oc在controller中定义WebViewJavascriptBridge,并定义需要桥接的webview

@property WebViewJavascriptBridge* bridge;
viewdidload or viewwillappear
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
[self.view addSubview:webView];
[WebViewJavascriptBridge enableLogging];
_bridge = [WebViewJavascriptBridge bridgeForWebView:webView];

6、在ios中和js中分别注册处理器

JS注册处理器(oc向js通信)

        bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) {
log('ObjC called testJavascriptHandler with', data)
var responseData = { 'Javascript Says':'Right back atcha!' }
log('JS responding with', responseData)
responseCallback(responseData)
}) //data是oc传给js的值,responseData是传回给oc的值

oc中调用js中的处理器,两种方式,一种有回调的block一种没有

    [_bridge callHandler:@"testJavascriptHandler" data:@{ @"foo":@"before ready" }]; //没有回调block的
    id data = @{ @"greetingFromObjC": @"Hi there, JS!" };
[_bridge callHandler:@"testJavascriptHandler" data:data responseCallback:^(id response) {
NSLog(@"testJavascriptHandler responded: %@", response);
}]; //有回调block的

OC注册处理器(js调用oc代码用)

    [_bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"testObjcCallback called: %@", data);
responseCallback(@"Response from testObjcCallback"); //回调给js
}];

js中调用oc的处理器(参数:处理器名,data,response回调)

    bridge.callHandler('testObjcCallback', {'foo': 'bar'}, function(response) {
log('JS got response', response)
})

另外:controller需要遵守UIWebView的协议

[_bridge setWebViewDelegate:self]; // 一定要放在viewdidload or viewwillappear最后

Back