MTLJWebKit
一套基于WKWebView的Objective-C和JavaScript交互解决方案,支持iOS 9.0
安装(iOS)
使用CocoaPods安装
将此添加到您的Podfile 中,然后运行 pod install
来安装。
pod 'MTLJWebKit', '~> 1.0.2'
使用方法
- 导入头文件
#import <MTLJWebKit/MTLJWebKit.h>
- 实例化MTLJWebViewController并设置originURL属性
MTLJWebViewController *webViewVC = [[MTLJWebViewController alloc] init];
webViewVC.originURL = xxxURL;
- 继承MTLJJSCommandHandlerBase类,重写executeCommand:responseHandler:方法并设置scheme属性,在ObjC中注册JSCommandHandler
[webViewVC registerJSCommandHandler:[MTLJJSCommandHandlerBaseSubClass new]];
- 继承MTLJJSCommandResponseBase类,重写executeResponse:responseData:方法并设置scheme、argument属性,在ObjC中调用JSCommandHandler
[webViewVC callJSCommandHandler:[MTLJJSCommandResponseBaseSubClass new]];
- 将
setupMTLJWebViewJavascriptBridge
复制粘贴到您的JS中
function setupMTLJWebViewJavascriptBridge(callback) {
if (window.MTLJWebViewJavascriptBridge) { return callback(MTLJWebViewJavascriptBridge); }
if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
window.WVJBCallbacks = [callback];
var WVJBIframe = document.createElement('iframe');
WVJBIframe.style.display = 'none';
WVJBIframe.src = 'mtljcommand://__bridge_loaded__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}
- 最后,调用
setupMTLJWebViewJavascriptBridge
然后使用这个bridge来注册处理器并调用ObjC处理器
setupMTLJWebViewJavascriptBridge(function(bridge) {
/* Initialize your app here */
bridge.registerHandler('mtljcommand://fetchFansInfo', function(data, responseCallback) {
log('ObjC called parameter with', data)
var responseData = { 'Javascript Says info':'lilei' }
log('JS responding parameter with', responseData)
responseCallback(responseData)
})
bridge.callHandler('mtljcommand://fetchPhoneInfo', {'platform': 'ios'}, function(response) {
log('JS got response', response)
})
})