我想把这行代码写在Swift

I want to write this line of code in Swift

我想把我用nodejs写的这段代码写在Swift

io.sockets.in('julia.girldeveloper@example.com').emit('chat', 'Hello i am julia');

我试过了,但没用:

socket.emit("chat", with: ["JLA" , "asdf.swift@gmail.com"])

您可以为 Swift 使用 Socket.IO 客户端。

import SocketIO

let manager = SocketManager(socketURL: URL(string: "http://localhost:8080")!, config: [.log(true), .compress])
let socket = manager.defaultSocket

socket.on(clientEvent: .connect) {data, ack in
    print("socket connected")
}

socket.on("currentAmount") {data, ack in
    guard let cur = data[0] as? Double else { return }

    socket.emitWithAck("canUpdate", cur).timingOut(after: 0) {data in
        socket.emit("update", ["amount": cur + 2.50])
    }

    ack.with("Got your currentAmount", "dude")
}

socket.connect()

您可以在 Swift 语言中使用以下代码。

import SocketIO
import Foundation

let serverURL = "YourServerURL"

class SocketOpration {

    static let shared = SocketOpration(socketURL: URL(string: serverURL)!)

    let socketURL: URL
    var socket:SocketIOClient!
    var manager:SocketManager!


   init(socketURL: URL) {
        self.socketURL = socketURL
        self.manager = SocketManager(socketURL: self.socketURL, config: [.log(false)])
        self.socket = self.manager.defaultSocket
   }

    func setup() {

          socket.on(clientEvent: .connect) {[weak self] data, ack in
              print("socket connected")
          }

          socket.on(clientEvent: .disconnect) {[weak self] data, ack in
            print("socket disconnected")
          }


        // Get emit Call via On method ( emit will fire from Node )

         socket.on("chat") { [weak self](data, ack) in
            if data.count > 0 {
            }
         }

    }

     func chatEmail(senderName: String, email: String) {

        socket.emit("chat", with: [senderName , email]])

    }

}

使用:-

SocketOpration.shared.chatEmail(senderName: "JLA", email: "asdf.swift@gmail.com")

干杯!!