WebViewJavascriptBridge 进行js 与native通信。
1, iOS端加载web页面、开启日志并给webView建立JS与OC的桥梁
- (void)viewWillAppear:(BOOL)animated {
if (_bridge) { return; }
// 1.加载网页
UIWebView* webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webView];
// 2.开启日志
[WebViewJavascriptBridge enableLogging];
// 3.给webView建立JS和OC的沟通桥梁
_bridge = [WebViewJavascriptBridge bridgeForWebView:webView];
[_bridge setWebViewDelegate:self];
//JS调用OC通过重定向url并取handlerName来调用,
//注册 js调用OC方法
[_bridge registerHandler:@"readID" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"readID 读身份证 called: %@", data);
responseCallback(@" readID back");
}];
[self renderButtons:webView];
[self loadExamplePage:webView];
}
iOS端注册与前端JS中对应的方法,获得回调,然后我们就可以在回调中做我们需要做的操作。
//OC 调用 js
- (void)callHandler:(id)sender {
id data = @{ @"greetingFromObjC": @"Hi there, oc调 JS!" };
//OC调用JS通过stringByEvaluatingJavaScriptFromString调用。
[_bridge callHandler:@"testJavascriptHandler" data:data responseCallback:^(id response) {
NSLog(@" 回到OC文件啦--- oc调js 打印回调 testJavascriptHandler responded: %@", response);
}];
}
//js 部分
<script>
window.onerror = function(err) {
log('window.onerror: ' + err)
}
function 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)
}
setupWebViewJavascriptBridge(function(bridge) {
var uniqueId = 1
function log(message, data) {
var log = document.getElementById('log')
var el = document.createElement('div')
el.className = 'logLine'
el.innerHTML = uniqueId++ + '. ' + message + ':<br/>' + JSON.stringify(data)
if (log.children.length) { log.insertBefore(el, log.children[0]) }
else { log.appendChild(el) }
}
//oc调用js
//H5调用 注册本地JS方法,注册后Native可通过JSBridge调用。调用后会将方法注册到本地变量messageHandlers 中
//注册一个供原生调用的api
bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) {
//log('ObjC called testJavascriptHandler with', data)
var responseData = { 'JavascriptSays':' oc 调js 返回数据 Right back atcha!' }
responseCallback(responseData)
})
document.body.appendChild(document.createElement('br'))
var callbackButton = document.getElementById('buttons').appendChild(document.createElement('button'))
callbackButton.innerHTML = 'Fire testObjcCallback'
callbackButton.onclick = function(e) {
e.preventDefault()
log('JS calling handler "testObjcCallback"')
//js调用oc
//H5调用 调用原生开放的api,调用后实际上还是本地通过url scheme触发。调用时会将回调id存放到本地变量responseCallbacks中
bridge.callHandler('readID', {'foo': 'bar'}, function(response) {
log('JS got response', response)
})
}
})
</script>
最后在dealloc方法调用清除缓存的方法: