有些项目需要用到Object-C和JavaScript之间的交互问题,本文着重介绍如何利用第三方库WebViewJavascriptBridge来实现Object-C和JavaScript的相互调用。
1、使用cocopads安装WebViewJavaScriptBridge
命令行进入项目根目录,新建Podfile文件,输入以下内容(以Cocopads1.1.0为例,版本不同,命令会有差别):
platform :ios, '8.0'
target 'BridgeDemo' do
pod 'WebViewJavascriptBridge', '~> 5.0'
end
保存Podfile的修改,执行pod install安装WebViewJavaScriptBridge。
2、先来介绍Object-C部分的代码
新建ViewController文件,以下是.m文件的代码部分
引入WebViewJavaScriptBridge头文件
#import "WebViewJavascriptBridge.h"
成员变量添加bridge和webView
@interface ViewController ()
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) WebViewJavascriptBridge *bridge;
@end
懒加载页面控件
#pragma mark - Lazy load element
// Create webview element
- (UIWebView *)webView
{
if (!_webView) {
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 80, WINDOW.width, WINDOW.height -80)];
}
return _webView;
}
// Create bridge
- (WebViewJavascriptBridge *)bridge
{
if (!_bridge) {
_bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView];
[_bridge setWebViewDelegate:self];
}
return _bridge;
}
在viewDidload方法中执行创建视图的方法 buildView
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self buildView];
}
buildView方法等实现如下:
- (void)buildView
{
[self.view addSubview:self.webView];
// 加载本地网页
[self loadExamplePage:self.webView];
// 启用调试功能
[WebViewJavascriptBridge enableLogging];
/**
* 注册名为testObjcCallback方法,该方法是JS调用OC使用到的,凭借方法名建立对应关系
* data -- JS传递给OC的参数
* responseCallback -- OC向JS反馈的回调方法
/
[self.bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"testObjcCallback called: %@", data);
responseCallback(@"Response from testObjcCallback");
}];
/*
* 注册名为testJavascriptHandler方法,该方法是OC调用JS使用到的,凭借方法名建立对应关系,该语句会在程序运行时自动执行
* data -- OC传递给JS的参数,该语句未添加回调方法
*/
[self.bridge callHandler:@"testJavascriptHandler" data:@{ @"foo":@"before ready" }];
// 创建若干按钮,触发后调用JS的方法
UIButton *btn0 = [self addButton:CGRectMake(10, 20, 80, 35) Title:@"Button0" SuperView:self.view Tag:100 Target:self Action:@selector(clickBtn:)];
[self.view addSubview:btn0];
UIButton *btn1 = [self addButton:CGRectMake(100, 20, 80, 35) Title:@"Button1" SuperView:self.view Tag:101 Target:self Action:@selector(clickBtn:)];
[self.view addSubview:btn1];
UIButton *btn2 = [self addButton:CGRectMake(190, 20, 80, 35) Title:@"Reload" SuperView:self.view Tag:102 Target:self.webView Action:@selector(reload)];
[self.view addSubview:btn2];
}
自定义封装按钮方法
- (UIButton *)addButton:(CGRect)frame Title:(NSString *)title SuperView:(UIView *)superView Tag:(NSInteger)tag Target:(id)target Action:(SEL)action
{
if ([superView viewWithTag:tag]) {
return (UIButton *)[superView viewWithTag:tag];
}
UIButton *btn = [[UIButton alloc] initWithFrame:frame];
[btn setTitle:title forState:UIControlStateNormal];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor redColor]];
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
btn.titleLabel.font = [UIFont systemFontOfSize:13.0];
btn.tag = tag;
return btn;
}
按钮点击方法,在这里,我将按钮的tag作为参数传递给JS
- (void)clickBtn:(UIButton )sender
{
id data = @{ @"tag": @(sender.tag) };
[_bridge callHandler:@"testJavascriptHandler" data:data responseCallback:^(id response) {
NSLog(@"testJavascriptHandler responded: %@", response);
}];
}
加载本地网页方法
- (void)loadExamplePage:(UIWebView)webView {
NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSString *appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
[webView loadHTMLString:appHtml baseURL:baseURL];
}
3、JavaScript实现部分
完整的JavaScript代码如下,备注在代码中
$(function() {
window.onerror = function(err) {
log('window.onerror: ' + err);
}
// Run bridge
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 + ':
' + JSON.stringify(data);
if (log.children.length) {
log.insertBefore(el, log.children[0]);
} else {
log.appendChild(el);
}
}
/**
* OC调用JS部分,凭借字符串testJavascriptHandler完成对应
* data -- OC向JS传递的参数
* responseCallback -- 回调方法
*/
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);
})
document.body.appendChild(document.createElement('br'));
// JS调用OC部分
var callbackButton = document.getElementById('buttons').appendChild(document.createElement('button'));
callbackButton.innerHTML = 'Fire testObjcCallback';
callbackButton.onclick = function(e) {
e.preventDefault();
log('JS calling handler "testObjcCallback"');
bridge.callHandler('testObjcCallback', {'foo': 'bar'}, function(response) {
log('JS got response', response);
});
};
});
});
// Set up bridge
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 = 'wvjbscheme://__BRIDGE_LOADED__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function() {
document.documentElement.removeChild(WVJBIframe)
}, 0);
}
Demo地址: https://pan.baidu.com/s/1qXWkBtq f7y2
更多详情,请访问Github:https://github.com/marcuswestin/WebViewJavascriptBridge