[英]Pass variable from Swift to javascript function
使用JSContext将变量传递给javascript函数时遇到问题。 错误显示stringToSend
未定义:
func sendSomething(stringToSend : String) {
appController?.evaluateInJavaScriptContext({ (context) -> Void in
context.evaluateScript("myJSFunction(stringToSend)")
}, completion: { (evaluated) -> Void in
print("we have completed: \(evaluated)")
})
}
这是我喜欢从Swift到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)")
})
}
调用此方法时,请确保在您的JavaScript上下文中实现了myJSFunction 。
使用callWithArguments时,您的stringToSend字符串将自动映射到javascript字符串。
字符串需要Swift的String Interpolation
,加上额外的引号,如下所示:
func sendSomething(stringToSend : String) {
appController?.evaluateInJavaScriptContext({ (context) -> Void in
context.evaluateScript("myJSFunction('\(stringToSend)')")
}, completion: { (evaluated) -> Void in
print("we have completed: \(evaluated)")
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.