Pass variable from Swift to javascript function

自闭症网瘾萝莉.ら 提交于 2019-12-11 11:53:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!