2016-05-25 21 views
13

Tôi cần phải bao gồm mã JavaScript trong mã Swift để có thể gọi một cuộc trò chuyện signalR, là có thể? Nếu không, tôi có thể chuyển đổi nó không?Tôi có thể chạy JavaScript bên trong mã Swift không?

sendmessage là một nút.

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

và mã signalr là:

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

Update # 1:

thay đổi câu hỏi một chút vì vậy nó không phải là khó hiểu mỗi @MartinR

Trả lời

27

Bạn có thể chạy JavaScript bên trong Swift!

Dưới đây là một ví dụ để giúp bạn bắt đầu:

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 sẽ Test Message: the message.

Bạn cũng có thể chạy mã JavaScript trong một UIWebView bằng cách gọi string​By​Evaluating​Java​Script(from:​) hoặc trong vòng một WKWebView gọi evaluate​Java​Script(_:​completion​Handler:​)

+0

nơi mà tôi phải viết mã đó? bạn có thể đưa ra ví dụ đầy đủ về điều đó không? –

+0

Bạn có biết cách tôi có thể nhập tệp JS vào Swift không? – JmJ

+0

Bạn có thể làm điều gì đó như: 'let jsSource = String.stringWithContentsOfFile (path +"/jsFile.js ")' – Daniel

Các vấn đề liên quan