我可以在Swift代码中运行JavaScript吗?

use*_*042 33 javascript signalr swift

我需要在Swift代码中包含JavaScript代码才能调用signalR聊天,这可能吗?如果没有,我可以转换它吗?

sendmessage 是一个按钮.

$(function () {
    // Declare a proxy to reference the hub.
    var chat = $.connection.chatHub;
    // Create a function that the hub can call to broadcast messages.
    chat.client.broadcastMessage = function (name, message) {
        // some code
    };

    // Start the connection.
    $.connection.hub.start().done(function () {
        $('#sendmessage').click(function () {
            // Call the Send method on the hub.
            chat.server.send('name', 'message');
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

signalr代码是:

    public void Send(string name, string message)
    {
        // Call the broadcastMessage method to update clients. 
        Clients.All.broadcastMessage(name, message);
    }
Run Code Online (Sandbox Code Playgroud)

更新#1:

改变了一点问题,所以每个@MartinR都不会混淆

Dan*_*iel 52

你可以在Swift里面运行JavaScript!

以下是您可以在Playground中运行的示例,以帮助您入门:

import JavaScriptCore

let jsSource = "var testFunct = function(message) { return \"Test Message: \" + message;}"

var context = JSContext()
context?.evaluateScript(jsSource)

let testFunction = context?.objectForKeyedSubscript("testFunct")
let result = testFunction?.call(withArguments: ["the message"])
Run Code Online (Sandbox Code Playgroud)

result会的Test Message: the message.

您还可以在WKWebView中调用evaluate Java Script(_:completion Handler :)来运行JavaScript代码.

您还可以通过调用字符串By Evaluating Java Script(from :)来在UIWebView中运行JavaScript ,但请注意,该方法已被弃用并标记为iOS 2.0-12.0.

  • 我必须在哪里编写该代码?你能给出一个完整的例子吗? (2认同)
  • @James 答案的代码中的所有内容都已更新 (2认同)

Ash*_*ish 6

使用  JavaScriptCore框架将JavaScript代码包含在Swift代码中。

您将最常处理的类是  JSContext。此类是执行JavaScript代码的实际环境(上下文)。

JSContext中的所有值  都是JSValue对象,因为JSValue类表示任何JavaScript值的数据类型。这意味着,如果您从Swift访问JavaScript变量和JavaScript函数,则两者均被视为JSValue对象。

我强烈建议您阅读有关JavaScriptCore框架的官方文档  。 

import JavaScriptCore


var jsContext = JSContext()


// Specify the path to the jssource.js file.
if let jsSourcePath = Bundle.main.path(forResource: "jssource", ofType: "js") {
    do {
        // Load its contents to a String variable.
        let jsSourceContents = try String(contentsOfFile: jsSourcePath)

        // Add the Javascript code that currently exists in the jsSourceContents to the Javascript Runtime through the jsContext object.
        self.jsContext.evaluateScript(jsSourceContents)
    }
    catch {
        print(error.localizedDescription)
    }
}  
Run Code Online (Sandbox Code Playgroud)

更多细节请参考本教程