我能在Swift代码中运行JavaScript吗?

49

我需要在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');
        });
    });
});

signalr 的代码是:

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

更新#1:

根据@MartinR的建议略微修改了问题,以使其更加清晰易懂。

2个回答

83

最后使用Swift 5.1进行测试

这里有一个你可以在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"])

result 的结果将会是 测试消息:the message

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

您也可以通过调用string​By​Evaluating​Java​Script(from:​)UIWebView中运行JavaScript代码,但请注意该方法已被弃用并标记为iOS 2.0-12.0。


2
我应该在哪里编写这段代码?你能给我一个完整的例子吗? - Abdulrahman Masoud
您知道如何将JS文件导入Swift中吗? - JmJ
1
无论您需要在哪里运行js - Daniel
@tresf,您介意分享最终的工作代码片段吗? - zmerr
2
@James,答案的代码已经全部更新。 - Daniel
显示剩余3条评论

14

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

你将会与最多处理的类是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)
    }
}  

更多细节请参考此教程


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接