1

使用 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)")
        })
    }
4

2 回答 2

4

以下是我喜欢从 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 String 将自动映射到 javascript 字符串。

于 2016-01-07T22:40:38.353 回答
2

该字符串需要 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)")
        })
    }
于 2016-01-07T21:46:07.543 回答