如何使用JavaScriptCore

时间:2017-10-30 21:14:08

标签: javascript ios swift javascriptcore

我正在尝试使用JSCore从Swift中的javascript SDK执行异步函数。我已经能够完成对脚本内容的评估和查看,但实际调用异步函数却没有成功。这是我的代码,以验证我甚至阅读了脚本。有关如何实现这一点的任何想法?

lazy var context: JSContext? = {
    let context = JSContext()

    guard let
        commonJSPath = Bundle.main.path(forResource: "test", ofType: "js") else {
            print("Unable to read resource files.")
            return nil
    }

    do {
        let common = try String(contentsOfFile: commonJSPath, encoding: String.Encoding.utf8)
        _ = context?.evaluateScript(common)
    } catch (let error) {
        print("Error while processing script file: \(error)")
    }

    return context
}()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    setupJS()

}

func setupJS(){
    guard let context = context else {
        print("JSContext not found.")
        return
    }

    let dictionary = context.objectForKeyedSubscript("MainObject").toDictionary()
    print(dictonary)
    //let script = "const {variableName} = FooJS;";
    //let result = context.evaluateScript(script)

}

我想做async function doSomething(){ return 'hello world!'; } console.log(await doSomething());

之类的事情

1 个答案:

答案 0 :(得分:1)

从swift调用javascript函数:

context.objectForKeyedSubscript("functionName_in_Javascript_file").call(withArguments: [])

为了让控制权回到swift,你可以定义一个从javascript中调用的块,如下所示:

// someString可能是javascript所需的结果。

let swiftHandler: @convention(block) (String) -> Void = {(someString) in
        //do something
    }

//使块可用于javasript,如下所示:

let swiftBlock = unsafeBitCast(swiftHandler, to: AnyObject.self)

context.setObject(swiftBlock, forKeyedSubscript: "swiftCallback" as (NSCopying & NSObjectProtocol)!)

//最后在您的javascript文件中,当您获得所需的结果时,只需使用您在上一步中给出的名称调用swift函数:

swiftCallback(result);