【问题标题】:Pass variable from Swift to javascript function将变量从 Swift 传递给 javascript 函数
【发布时间】:2016-01-07 21:46:07
【问题描述】:

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

【问题讨论】:

    标签: javascript swift tvml tvjs


    【解决方案1】:

    这是我喜欢从 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 字符串。

    【讨论】:

    • 如果你想发送更复杂的对象,你会怎么做?我试过 JSExport 但它没有用
    【解决方案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)")
            })
        }
    

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 2016-08-21
      • 2015-05-02
      • 2015-07-23
      • 1970-01-01
      • 2017-04-30
      • 2018-12-14
      • 2014-10-31
      相关资源
      最近更新 更多