🏝 Oasis JSBridge
评估 JavaScript 代码,并在 iOS 中映射 Swift 和 JavaScript 之间的值、对象和函数。
由
特点
基于 JavascriptCore,并提供对以下内容的额外支持:
- 支持 JS promises 的双向支持
- 一些 JS 运行时功能的功能填充(例如 setTimeout、XmlHttpRequest、console、localStorage)
支持类型
OasisJSBridge 支持 JavaScriptCore 支持的所有类型。Swift (ObjC) 类型可以通过 JSExport 协议导出至 JavaScript。
Swift 目前尚不支持 promise/deffered 调用,为了支持此类 API,OasisJSBridge 提供了 JavascriptPromise 和 NativePromise 对象。
使用方法
// define Swift type that can be sent to Javascript
@objc protocol VehicleProtocol: JSExport {
var brand: String? { get }
}
@objc class Vehicle: NSObject, VehicleProtocol {
var brand: String?
}
let vehicle = Vehicle()
vehicle.brand = "bmw"
// create an instance of JavascriptInterpreter
let interpreter = JavascriptInterpreter()
// define a function in Swift
let toUppercase: @convention(block) (String) -> String = { $0.uppercased() }
interpreter.setObject(toUppercase, forKey: "toUppercase")
// load Javascript, use previously defined toUppercase function
interpreter.evaluateString(js: """
var testObject = {
testMethod: function(vehicle, callback) {
return toUppercase(vehicle.brand)
}
};
""")
// call Javascript function
interpreter.call(object: nil, functionName: "testObject.testMethod", arguments: [vehicle], completion: { value in
XCTAssertEqual(value?.toString(), "BMW")
})
授权协议
Copyright (C) 2019 ProSiebenSat1.Digital GmbH.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://apache.ac.cn/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.