|
@@ -22,7 +22,7 @@ func createJSContext() -> JSContext {
|
|
|
// 注入 console.log
|
|
|
ctx?.evaluateScript("var console = { log: function(message) { _consoleLog(message) } }")
|
|
|
let consoleLog: @convention(block) (String) -> Void = { message in
|
|
|
- print("JavaScript Console.log: " + message)
|
|
|
+ print("JS 打印: \(message)")
|
|
|
}
|
|
|
ctx?.setObject(unsafeBitCast(consoleLog, to: AnyObject.self), forKeyedSubscript: "_consoleLog" as (NSCopying & NSObjectProtocol)?)
|
|
|
|
|
@@ -58,7 +58,7 @@ func createJSContext() -> JSContext {
|
|
|
// 捕捉JS运行异常
|
|
|
ctx?.exceptionHandler = { context, exception in
|
|
|
if let exception = exception {
|
|
|
- print("JavaScript Exception: \(exception)")
|
|
|
+ print("JS 执行异常: \(exception)")
|
|
|
}
|
|
|
}
|
|
|
|
|
@@ -66,21 +66,29 @@ func createJSContext() -> JSContext {
|
|
|
}
|
|
|
|
|
|
func testSearch(keyword: String, ctx: JSContext) -> Void {
|
|
|
- if let jsFunction = ctx.objectForKeyedSubscript("search") {
|
|
|
- let promise = jsFunction.call(withArguments: ["周杰伦", nil])
|
|
|
- // 检查返回值是否为 Promise
|
|
|
- // 获取 Promise 的 then 函数
|
|
|
- if let thenFunction = promise?.objectForKeyedSubscript("then") {
|
|
|
+ if let searchFunction = ctx.objectForKeyedSubscript("search") {
|
|
|
+ print(searchFunction)
|
|
|
+ let result = searchFunction.call(withArguments: ["周杰伦", nil])
|
|
|
+ print(result?.toString())
|
|
|
+ let resolveHandler: @convention(block) (JSValue?) -> Void = { resolvedValue in
|
|
|
+ if let value = resolvedValue {
|
|
|
+ print("搜索成功: ", value)
|
|
|
+ }
|
|
|
+ }
|
|
|
+ let rejectHandler: @convention(block) (JSValue?) -> Void = { rejectedValue in
|
|
|
+ if let value = rejectedValue {
|
|
|
+ print("搜索失败:", value)
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if let thenFunction = result?.objectForKeyedSubscript("then") {
|
|
|
+ print("Then:", thenFunction.toString())
|
|
|
// 调用 then 函数,并传入回调函数
|
|
|
- thenFunction.call(withArguments: [ { (resolvedValue: JSValue?) in
|
|
|
- if let value = resolvedValue {
|
|
|
- print("搜索成功", value)
|
|
|
- }
|
|
|
- }, { (rejectedReason: JSValue?) in
|
|
|
- if let reason = rejectedReason {
|
|
|
- print("搜索失败", reason)
|
|
|
- }
|
|
|
- }])
|
|
|
+ thenFunction.call(withArguments: [unsafeBitCast(resolveHandler, to: AnyObject.self)])
|
|
|
+ }
|
|
|
+ if let catchFunction = result?.objectForKeyedSubscript("catch") {
|
|
|
+ print("Catch:", catchFunction.toString())
|
|
|
+ // 调用 catch 函数,并传入回调函数
|
|
|
+ catchFunction.call(withArguments: [unsafeBitCast(rejectHandler, to: AnyObject.self)])
|
|
|
}
|
|
|
}
|
|
|
}
|