4

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?

4
  • May be duplicate http://stackoverflow.com/questions/24595692/swift-blocks-not-working Commented Apr 1, 2016 at 4:04
  • Did you ever figure this out? I'm trying to do this right now. Commented May 24, 2016 at 21:53
  • I have it completely working with Objective C, would this help you? Commented May 25, 2016 at 8:14
  • Hello @Sprotte. How did you solve this issue? Commented Dec 28, 2017 at 3:20

1 Answer 1

3

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried implementing this solution, but I can't get it to work. Is the context that you pass to the callback just the generic JSCore context previously set up?
@Julia Yes it's the same JSContext as theJSFunction is running in. I remember calling a 3 arg swift block with 2 args on js side being a problem, might want to make sure number of args is same on both sides. Also in my old code I end up using (JSValue) -> Void instead of (JSValue?) -> Void for some reason

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.