Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I run JavaScript inside Swift code?

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

like image 936
user1019042 Avatar asked May 25 '16 10:05

user1019042


People also ask

Can I use JavaScript in Swift?

The JavaScriptCore framework provides the ability to evaluate JavaScript programs from within Swift, Objective-C, and C-based apps. You can use also use JavaScriptCore to insert custom objects into the JavaScript environment.

Can I use JavaScript in Xcode?

Xcode is an Objective-C and Swift IDE, used primarily for iOS and MacOS development. It has no inherent JavaScript support, and while there may be some way to do iOS development in JS, it almost certainly requires a secondary piece of software to compile JS into one of the languages Xcode supports.

Where can I run my JavaScript code?

To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.

Can JavaScript run on any platform?

Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine. The browser has an embedded engine sometimes called a “JavaScript virtual machine”. Different engines have different “codenames”.


2 Answers

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.

like image 72
Daniel Avatar answered Oct 06 '22 23:10

Daniel


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

like image 26
Ashish Avatar answered Oct 07 '22 01:10

Ashish