ECMASwift 旨在实现一个 Browser API 的微小子集(主要与网络相关),以简化 iOS/macOS 应用程序和 Web 之间的代码共享。
ECMASwift 将以下浏览器 API 暴露给 JavascriptCore,其中一些 API 尚未完成,欢迎贡献。
在 Javascript 中
// Define an async function to fetch some dummy data in Javascript
async function fetchProducts() {
try {
const res = await fetch("https://google.com")
return await res.json()
} catch(error) {
console.log(error)
}
}
在 Swift 中
import ECMASwift
import JavaScriptCore
// Initialise the runtime
let runtime = JSRuntime()
// Load the javascript source file defined above, alternatively JS can be written inline.
let javascriptSource = try! String(contentsOfFile: "./example.js")
// Evaluate the script
_ = runtime.context.evaluateScript(javascriptSource)
// Call the `fetchProducts` function defined in the source file.
let result = try! await runtime.context.callAsyncFunction(key: "fetchProducts")
// Print the result
print(result.toString())