Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  108] [ 3]  / answers: 1 / hits: 43795  / 8 Years ago, wed, may 25, 2016, 12:00:00

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


More From » swift

 Answers
70

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.


[#62038] Monday, May 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorr

Total Points: 193
Total Questions: 86
Total Answers: 105

Location: Pitcairn Islands
Member since Thu, Jun 24, 2021
3 Years ago
victorr questions
Fri, Nov 13, 20, 00:00, 4 Years ago
Sat, Jul 25, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;