Chopper
示例
使用
git clone https://github.com/JianweiWangs/Chopper.git
cd Chopper
make
来快速获取和构建源代码。
要运行示例项目,首先克隆仓库,然后从根目录运行 make
。
有一些脚本可以帮助您开发和提交 PR。
# install dependence and open project
make
# install dependence
make install
# build test
make test
# open project
make open
# quit Xcode
make quit
在您提交 PR 之前,请确保测试通过。
使用
快速开始
推荐
- 创建一个 JavaScript 模块
import Chopper
class TestModule: JavaScriptModuleInterface {
// test module
var module: String {
return "test"
}
// actions, you can add any action you want
var moduleMapping: [String : Dispatch] {
return [
"showAlert" : showAlert
]
}
func showAlert(message: JavaScriptMessage, callback: @escaping (Bool, [String : Any]) -> Void) {
print(message.context.frameViewController)
print(message.context.viewController)
print(message)
callback(true, ["code" : "0"])
}
}
- 创建桥梁,将模块注入到 dataSource
import Chopper
class ViewController: UIViewController {
@IBOutlet weak var webview: WKWebView!
var jsbridge: JavaScriptBridge!
override func viewDidLoad() {
super.viewDidLoad()
jsbridge = JavaScriptBridge(dataSource: self)
}
}
extension ViewController: JavaScriptBridgeDataSource {
// you can return multiple module instance, the modules more there are, the more actions can be handle
var modules: [JavaScriptModuleInterface] {
return [TestModule()]
}
var viewController: UIViewController {
return self
}
var webView: WKWebView {
return self.webview
}
}
- JavaScript 调用
dispatch('test', 'showAlert', {
'title': 'Chopper',
'message': 'this is a js call native test'
}, function (success, params) {
alert('callback isSuccess: ' + success + ' params: ' + params.code)
})
您也可以通过便捷的注册调用桥梁的 webview 脚本
jsbridge.regist(module: "convenience", action: "showAlert") { [unowned self] (message, callback) in
// recommand use message.context.viewController instead of `self`
// if use self, use weak or unowned to avoid reference cycle
print(message.context.viewController == self) // true
print(message)
callback(true, ["code": 1])
}
需求
Swift 4.0
,iOS 8.0
安装
Chopper 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod 'Chopper'
作者
JianweiWangs,[email protected]
许可证
Chopper 在 MIT 许可下可用。更多信息请参阅 LICENSE 文件。