我需要在 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 代码打电话evaluateJavaScript(_:completionHandler:) .
您还可以在 UIWebView 中运行 JavaScript调用stringByEvaluatingJavaScript(from:) ,但请注意该方法已弃用并标记为 iOS 2.0–12.0。
关于javascript - 我可以在 Swift 代码中运行 JavaScript 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37434560/