将变量从 Swift 传递到 javascript 函数
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 的 String Interpolation
,加上额外的引号,如下所示:
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)")
})
}
确保 myJSFunction 在您调用此方法时在您的 javascript 上下文中实现。
当使用 callWithArguments.
时,您的 stringToSend 字符串将自动映射到 javascript 字符串
使用 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 的 String Interpolation
,加上额外的引号,如下所示:
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)")
})
}
确保 myJSFunction 在您调用此方法时在您的 javascript 上下文中实现。
当使用 callWithArguments.
时,您的 stringToSend 字符串将自动映射到 javascript 字符串