Ad

How To Emit An Event In Socket.io Swift4

- 1 answer

I'm trying to emit an event when user join the chat room. So I have 2 classes:

  • SocketIOManager
  • ViewController

SocketIOManager code:

import SocketIO

class SocketIOManager: NSObject {

    static let manager = SocketManager(socketURL: URL(string: "https://myurl.com:443")!, config: [.log(true), .compress])
    static let socket = manager.defaultSocket

    class func connectSocket(){
        self.manager.config = SocketIOClientConfiguration(
            arrayLiteral: .connectParams(["token": myToken), .secure(true)
        )
        socket.connect()
    }

    class func connectToChatRoom(chat: String, user: String){
        let jsonDic = ["chat": chat,
                       "user": user]

        print("CHEKING SOCKET CONNECTION 1-ST TIME - \(socket.status)") // This gives me - connecting

        socket.emit("join", jsonData)

        print("CHEKING SOCKET CONNECTION 2-ND TIME - \(socket.status)") // This gives me - connecting
    }

    class func isSocketConnected() -> Bool{
        if socket.status == .connected {
            return true
        }
        return false
    }
}

In my ViewController I do - first of all I connect the socket. Then I'm trying to emit.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        SocketIOManager.connectSocket()
        SocketIOManager.connectToChatRoom(chat: chatID, user: myID)

        print("\(SocketIOManager.isSocketConnected())")  //This gives me "false"
    }
}

And after all I get an error in my log from Socket.IO: Tried emitting join when not connected.

CHEKING SOCKET CONNECTION 1-ST TIME - connecting
2018-03-27 12:26:04.895072+0300 MyApp[3760:1940922] LOG SocketIOClient{/}: Handling event: error with data: ["Tried emitting join when not connected"]
CHEKING SOCKET CONNECTION 2-ND TIME - connecting
false

Am I doing emit right? How do you perform emit with Socket.IO?

Ad

Answer

Sockets require a connection before emit is called. For this purpose Socket.IO has a listener socket.on ("connect"). So after we got status connected we can emit.

socket.on("connect") { _, _ in
        print("socket connected")
        socket.emit("your_event", jsonObject)
    }
Ad
source: stackoverflow.com
Ad