iOS WebViewJavascriptBridge的使用

WebViewJavascriptBridge

主要作用

实现了OC与JS之间的交互,可以相互调用,传值。

OC引用

1可以通过CocoaPods直接引入到工程中

pod "WebViewJavascriptBridge"

2.直接下载到本地添加到工程中

OC中的代码示例

- (void)viewDidLoad {
  [super viewDidLoad];

  UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
  [self.view addSubview:webView];

  NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
  NSString *appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
  NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
  [webView loadHTMLString:appHtml baseURL:baseURL];

  // 开启日志
    [WebViewJavascriptBridge enableLogging];

  // 给哪个webview建立JS与OjbC的沟通桥梁
  self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView];
  [self.bridge setWebViewDelegate:self];
  [self renderButtons:webView];

  // JS主动调用OjbC的方法
  // 这是JS会调用getUserIdFromObjC方法,这是OC注册给JS调用的
  // JS需要回调,当然JS也可以传参数过来。data就是JS所传的参数,不一定需要传
  // OC端通过responseCallback回调JS端,JS就可以得到所需要的数据
  [self.bridge registerHandler:@"getUserIdFromObjC" handler:^(id data, WVJBResponseCallback responseCallback) {
    NSLog(@"js call getUserIdFromObjC, data from js is ncsjndjsn%@", data);
    if (responseCallback) {
      // 反馈给JS
      responseCallback(@{@"userId": @"123456"});
    }
  }];
  [self.bridge registerHandler:@"getBlogNameFromObjC" handler:^(id data, WVJBResponseCallback responseCallback) {
    NSLog(@"js call getBlogNameFromObjC, data from js is %@", data);
    if (responseCallback) {
      // 反馈给JS
      responseCallback(@{@"blogName": @"标哥的技术博客"});
    }
  }];

  [self.bridge callHandler:@"getUserInfos" data:@{@"name": @"标哥"} responseCallback:^(id responseData) {
    NSLog(@"from js: %@", responseData);
  }];
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
  NSLog(@"webViewDidStartLoad");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
  NSLog(@"webViewDidFinishLoad");
}
- (void)renderButtons:(UIWebView*)webView {
  UIFont* font = [UIFont fontWithName:@"HelveticaNeue" size:12.0];

  UIButton *callbackButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  [callbackButton setTitle:@"打开博文" forState:UIControlStateNormal];
  [callbackButton addTarget:self action:@selector(onOpenBlogArticle:) forControlEvents:UIControlEventTouchUpInside];
  [self.view insertSubview:callbackButton aboveSubview:webView];
  callbackButton.frame = CGRectMake(10, 400, 100, 35);
  callbackButton.titleLabel.font = font;

  UIButton* reloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  [reloadButton setTitle:@"刷新webview" forState:UIControlStateNormal];
  [reloadButton addTarget:webView action:@selector(reload) forControlEvents:UIControlEventTouchUpInside];
  [self.view insertSubview:reloadButton aboveSubview:webView];
  reloadButton.frame = CGRectMake(110, 400, 100, 35);
  reloadButton.titleLabel.font = font;
}
- (void)onOpenBlogArticle:(id)sender {
  // 调用打开本demo的博文
  [self.bridge callHandler:@"openWebviewBridgeArticle" data:nil];
}

JS中的调用

      /*这段代码是固定的,必须要放到js中*/
      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)
      }
      /*与OC交互的所有JS方法都要放在此处注册,才能调用通过JS调用OC或者让OC调用这里的JS*/
      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) } } /* Initialize your app here */ /*我们在这注册一个js调用OC的方法,不带参数,且不用ObjC端反馈结果给JS:打开本demo对应的博文*/ bridge.registerHandler('openWebviewBridgeArticle', function() { log("openWebviewBridgeArticle was called with by ObjC") }) /*JS给ObjC提供公开的API,在ObjC端可以手动调用JS的这个API。接收ObjC传过来的参数,且可以回调ObjC*/ bridge.registerHandler('getUserInfos', function(data, responseCallback) { log("Get user information from ObjC: ", data) responseCallback({'userId': '123456', 'blog': '标哥的技术博客'}) }) /*JS给ObjC提供公开的API,ObjC端通过注册,就可以在JS端调用此API时,得到回调。ObjC端可以在处理完成后,反馈给JS,这样写就是在载入页面完成时就先调用*/ bridge.callHandler('getUserIdFromObjC', function(responseData) { log("JS call ObjC's getUserIdFromObjC function, and js received response:", responseData) }) document.getElementById('blogId').onclick = function (e) { log('js call objc: getBlogNameFromObjC') bridge.callHandler('getBlogNameFromObjC', {'blogURL': 'http://www.henishuo.com'}, function(response) { log('JS got response', response) }) } })

你可能感兴趣的:(iOS)