MTLJWebKit 1.0.3

MTLJWebKit 1.0.3

liangjie 维护。



 
依赖关系
Masonry~> 1.1.0
ZipArchive~> 1.4.0
 

  • 作者
  • lj

MTLJWebKit

一套基于WKWebView的Objective-C和JavaScript交互解决方案,支持iOS 9.0

安装(iOS)

使用CocoaPods安装

将此添加到您的Podfile 中,然后运行 pod install 来安装。

pod 'MTLJWebKit', '~> 1.0.2'

使用方法

  1. 导入头文件
#import <MTLJWebKit/MTLJWebKit.h>
  1. 实例化MTLJWebViewController并设置originURL属性
MTLJWebViewController *webViewVC = [[MTLJWebViewController alloc] init];
webViewVC.originURL = xxxURL;
  1. 继承MTLJJSCommandHandlerBase类,重写executeCommand:responseHandler:方法并设置scheme属性,在ObjC中注册JSCommandHandler
[webViewVC registerJSCommandHandler:[MTLJJSCommandHandlerBaseSubClass new]];
  1. 继承MTLJJSCommandResponseBase类,重写executeResponse:responseData:方法并设置scheme、argument属性,在ObjC中调用JSCommandHandler
[webViewVC callJSCommandHandler:[MTLJJSCommandResponseBaseSubClass new]];
  1. 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)
}
  1. 最后,调用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)
    })
})