OC与JS交互 - WebViewJavascriptBridge

WebViewJavascriptBridge是第三方框架,详细介绍可以参考下面这篇文章
https://juejin.im/post/5cecd746e51d45778f076cac

WebViewJavascriptBridge的使用

附上框架地址 WebViewJavascriptBridge

1. 引入头文件,声明bridge属性

#import "WebViewJavascriptBridge.h"

@property (nonatomic, strong) WebViewJavascriptBridge *bridge;

2. 初始化bridge

// 初始化
self.bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView];
// 如果你要在VC中实现 UIWebView的代理方法 就实现下面的代码(否则省略)
// [self.bridge setWebViewDelegate:self];

3. 注册handler,提供给JS调用

[self.bridge registerHandler:@"jsCallsOC" handler:^(id data, WVJBResponseCallback responseCallback) {    
    NSLog(@"currentThread == %@",[NSThread currentThread]);
    NSLog(@"data = %@", data);
    NSLog(@"responseCallback = %@", responseCallback);    
}];

4. callHandler,OC调动JS时使用

- (void)login {
    [self.bridge callHandler:@"OCCallJSFunction" data:@"oc调用js" responseCallback:^(id responseData) {
        NSLog(@"currentThread == %@",[NSThread currentThread]);
        NSLog(@"OC调用完JS后的回调:%@",responseData);
    }];
}

5. 拷贝这段配置到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 = 'https://__bridge_loaded__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}

6. 最后,在JS里调用setupWebViewJavascriptBridge,注册OC-->JS的处理程序 和 JS调用OC处理程序

setupWebViewJavascriptBridge(function(bridge) {

    bridge.registerHandler('OCCallJSFunction', function(data, responseCallback) {
        console.log("JS Echo called with:", data)
        responseCallback(data)
    })
    bridge.callHandler('jsCallsOC', {'Spirej':'18'}, function responseCallback(responseData) {
        console.log("JS received response:", responseData)
    })
})

文中所有示例demo可以在这里下载
https://github.com/SPIREJ/OCJS

你可能感兴趣的:(OC与JS交互 - WebViewJavascriptBridge)