Sprotte
Sprotte

Reputation: 541

JavaScriptCore call function with callback Swift

Im trying to call a Javascript Function with an callback from Swift and i dont get it working.

What i have is:

Javascript:

        global.calculateWithCb = function(temp,cb){
            cb(5 * temp)
        }

        global.calculate = function(temp) {
            return 5 * temp
        }

Swift:

        let context = JSContext()
        let scriptURL =        NSURL(fileURLWithPath: String("XXX/bundle.js"))
        let script : String = try String(contentsOfURL:scriptURL, encoding: NSUTF8StringEncoding)

        var jsSource: String! = script
        jsSource = "var window = this; \(jsSource)"
        context.evaluateScript(jsSource)

        let calculate = context.objectForKeyedSubscript("calculate")
        let output = calculate.callWithArguments([40]).toNumber()

So the calculate function is working like expected but i really don't know how to pass a block as a callback argument. Im searching a lot in the web but i don't find any hint maybe somebody can point me in the right direction?

Upvotes: 4

Views: 2876

Answers (1)

barissenkal
barissenkal

Reputation: 31

You need to manually init a JSValue with a @convention(block) swift block before calling as argument.

let testBlock : @convention(block) (JSValue?) -> Void = { calledBackValue in
    print("calledBackValue:", calledBackValue)
}
let callback = JSValue.init(object: testBlock, in: context)
// ...
jsFunctionToCallWithCallback.call(withArguments: [42, callback])
var theJSFunction = function(val, callback) {
    // Do smt...
    callback(val);
}

Upvotes: 3

Related Questions