gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:20:17 25 4
gpt4 key购买 nike

我需要在 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 不会混淆

最佳答案

最后使用 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 将是 Test Message: the message

您还可以在 WKWebView 中运行 JavaScript 代码打电话evaluate​Java​Script(_:​completion​Handler:​) .

您还可以在 UIWebView 中运行 JavaScript调用string​By​Evaluating​Java​Script(from:​) ,但请注意该方法已弃用并标记为 iOS 2.0–12.0。

关于javascript - 我可以在 Swift 代码中运行 JavaScript 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37434560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com