问题
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)")
})
}
回答1:
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.
回答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)")
})
}
来源:https://stackoverflow.com/questions/34665754/pass-variable-from-swift-to-javascript-function