Pass variable from Swift function to javascript

Failed to use JSContext to pass variable to javascript function. The error says stringToSend undefined:

 func sendSomething(stringToSend : String) { appController?.evaluateInJavaScriptContext({ (context) -> Void in context.evaluateScript("myJSFunction(stringToSend)") }, completion: { (evaluated) -> Void in print("we have completed: \(evaluated)") }) } 
+1
source share
2 answers

Here's how I like to communicate with Swift in 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 calling this method.

The stringToSend string will automatically be matched with the javascript string when using callWithArguments .

+3
source

The string is needed by Swift String Interpolation , plus additional quotation marks, for example:

 func sendSomething(stringToSend : String) { appController?.evaluateInJavaScriptContext({ (context) -> Void in context.evaluateScript("myJSFunction('\(stringToSend)')") }, completion: { (evaluated) -> Void in print("we have completed: \(evaluated)") }) } 
+2
source

All Articles