Pass variable from Swift to javascript function
Asked Answered
P

2

1

Having trouble using JSContext to pass a variable to a javascript function. The error says stringToSend is undefined:

func sendSomething(stringToSend : String) {
        appController?.evaluateInJavaScriptContext({ (context) -> Void in
            context.evaluateScript("myJSFunction(stringToSend)")
            }, completion: { (evaluated) -> Void in
                print("we have completed: \(evaluated)")
        })
    }
Perrins answered 7/1, 2016 at 21:46 Comment(0)
U
4

Here is how I like to communicate from Swift to Javascript:

func sendSomething(stringToSend : String) {
    appController?.evaluateInJavaScriptContext({ (context) -> Void in

       //Get a reference to the "myJSFunction" method that you've implemented in JavaScript
       let myJSFunction = evaluation.objectForKeyedSubscript("myJSFunction")

       //Call your JavaScript method with an array of arguments
       myJSFunction.callWithArguments([stringToSend])

       }, completion: { (evaluated) -> Void in
          print("we have completed: \(evaluated)")
    })
}

Make sure myJSFunction is implemented in your javascript context when you call this method.

Your stringToSend String will automatically be mapped to a javascript string when using callWithArguments.

Urushiol answered 7/1, 2016 at 22:40 Comment(1)
How would you do it if you want to send more complex Objects? I tried JSExport but it didnt workUnsearchable
P
2

The string needed Swift's String Interpolation, plus extra quotes, like this:

func sendSomething(stringToSend : String) {
        appController?.evaluateInJavaScriptContext({ (context) -> Void in
            context.evaluateScript("myJSFunction('\(stringToSend)')")
            }, completion: { (evaluated) -> Void in
                print("we have completed: \(evaluated)")
        })
    }
Perrins answered 7/1, 2016 at 21:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.