2016-05-25 11 views
13

Devo includere il codice JavaScript nel codice Swift per poter chiamare una chat signalR, è possibile? In caso contrario, posso convertirlo?Posso eseguire JavaScript nel codice Swift?

sendmessage è un pulsante.

$(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'); 
     }); 
    }); 
}); 

e il codice signalr è:

public void Send(string name, string message) 
    { 
     // Call the broadcastMessage method to update clients. 
     Clients.All.broadcastMessage(name, message); 
    } 

Update # 1:

mutata domanda un po 'in modo che non è fonte di confusione per @MartinR

risposta

27

È possibile eseguire JavaScript all'interno di Swift!

Ecco un esempio per iniziare:

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.callWithArguments(["the message"]) 

result sarebbe Test Message: the message.

È inoltre possibile eseguire codice JavaScript all'interno di un UIWebView chiamando string​By​Evaluating​Java​Script(from:​) oa una WKWebView chiamando evaluate​Java​Script(_:​completion​Handler:​)

+0

dove devo scrivere quel codice? puoi dare un esempio completo di questo? –

+0

Sai come ho potuto importare il file JS in Swift? – JmJ

+0

Puoi fare qualcosa del tipo: 'let jsSource = String.stringWithContentsOfFile (path +"/jsFile.js ")' – Daniel

Problemi correlati