将变量从Swift传递到javascript函数

问题描述:

使用JSContext将变量传递给javascript函数时遇到麻烦.错误显示stringToSend未定义:

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)")
        })
    }

这是我喜欢从Swift到Java进行通信的方式:

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)")
    })
}

在调用此方法时,请确保在您的JavaScript上下文中实现了 myJSFunction .

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

使用 callWithArguments 时,您的 stringToSend 字符串将自动映射到javascript字符串.

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