52

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 is a button.

$(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:

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

2 Answers 2

85

Last tested with Swift 5.1

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 would be Test Message: the message.

You also can run JavaScript code within a WKWebView calling evaluate​Java​Script(_:​completion​Handler:​).

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.

8
  • 2
    where i must write that code ? can you give as a full example of that ? Commented Oct 13, 2016 at 8:29
  • Do you know how I could import the JS file into Swift?
    – JmJ
    Commented Sep 11, 2017 at 23:06
  • You can do something like: let jsSource = String.stringWithContentsOfFile(path+"/jsFile.js")
    – Daniel
    Commented Sep 12, 2017 at 7:10
  • 1
    Wherever you need to run js
    – Daniel
    Commented May 1, 2018 at 6:58
  • 2
    @James everything has already been updated in the answer's code
    – Daniel
    Commented Sep 27, 2021 at 15:18
15

Using JavaScriptCore framework include JavaScript code in Swift code.

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

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.

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

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

more details refer this tutorial

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.