我可以在Swift代码中运行JavaScript吗? [英] Can I run JavaScript inside Swift code?

查看:182
本文介绍了我可以在Swift代码中运行JavaScript吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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都不会混淆

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

推荐答案

你可以在Swift中运行JavaScript!

You can run JavaScript inside Swift!

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

Here is an example you can run in Playground 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?.call(withArguments: ["the message"])

result 将是测试消息:消息

您还可以在 WKWebView 调用评估Java脚本(_:完成处理程序:)

您还可以在 UIWebView ,致电 string By评估Java脚本(来自:),但请注意该方法已被弃用并标记为iOS 2.0-12.0。

You can also run JavaScript within a UIWebView by calling string​By​Evaluating​Java​Script(from:​), but note that that method has been deprecated and is marked as iOS 2.0–12.0.

这篇关于我可以在Swift代码中运行JavaScript吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆