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

时间:2022-02-22 04:27:11

I need to include JavaScript code in Swift code to be able to call a signalR chat, is that possible? If not, can I convert it?

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

sendmessage is a button.

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');
        });
    });
});

and the signalr code is:

信号器代码是:

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

Update #1:

更新#1:

changed question a little bit so it is not confusing per @MartinR

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

2 个解决方案

#1


36  

You can run JavaScript inside Swift!

你可以在Swift里面运行JavaScript!

Here is an example to get you started:

这是一个让你入门的例子:

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.callWithArguments(["the message"])

result would be Test Message: the message.

结果将是测试消息:消息。

You also can run JavaScript code within a UIWebView by calling string​By​Evaluating​Java​Script(from:​) or within a WKWebView calling evaluate​Java​Script(_:​completion​Handler:​)

您还可以通过调用字符串By Evaluating Java Script(from :)或在WKWebView中调用evaluate Java Script(_:completion Handler :)来在UIWebView中运行JavaScript代码。

#2


3  

Using JavaScriptCore framework include JavaScript code in Swift code.

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

The class that you’ll be dealing the most with, is JSContext. This class is the actual environment (context) that executes your JavaScript code.

您将与之交易最多的类是JSContext。此类是执行JavaScript代码的实际环境(上下文)。

All values in JSContext, are JSValue objects, as the JSValue class represents the datatype of any JavaScript value. That means that if you access a JavaScript variable and a JavaScript function from Swift, both are considered to be JSValue objects.

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

I strongly advise you to read the official documentation regarding the JavaScriptCore framework

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

// 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)
    }
}  

more details refer this tutorial

更多细节请参阅本教程

#1


36  

You can run JavaScript inside Swift!

你可以在Swift里面运行JavaScript!

Here is an example to get you started:

这是一个让你入门的例子:

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.callWithArguments(["the message"])

result would be Test Message: the message.

结果将是测试消息:消息。

You also can run JavaScript code within a UIWebView by calling string​By​Evaluating​Java​Script(from:​) or within a WKWebView calling evaluate​Java​Script(_:​completion​Handler:​)

您还可以通过调用字符串By Evaluating Java Script(from :)或在WKWebView中调用evaluate Java Script(_:completion Handler :)来在UIWebView中运行JavaScript代码。

#2


3  

Using JavaScriptCore framework include JavaScript code in Swift code.

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

The class that you’ll be dealing the most with, is JSContext. This class is the actual environment (context) that executes your JavaScript code.

您将与之交易最多的类是JSContext。此类是执行JavaScript代码的实际环境(上下文)。

All values in JSContext, are JSValue objects, as the JSValue class represents the datatype of any JavaScript value. That means that if you access a JavaScript variable and a JavaScript function from Swift, both are considered to be JSValue objects.

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

I strongly advise you to read the official documentation regarding the JavaScriptCore framework

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

// 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)
    }
}  

more details refer this tutorial

更多细节请参阅本教程