Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect with Socket.io? Swift 4

I have read the latest documentation of Socket.io for Swift. And there is an example of a new connection:

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

So I have created a class SocketIOManager, like this:

class SocketIOManager: NSObject {

    static let manager = SocketManager(socketURL: URL(string: "myurl.com:443"))
    static let socket = manager.defaultSocket

    class func connectSocket(){
        socket.connect()
    }

    class func reciveMessage(){    
            socket.on("new-message-mob") { (dataArray, ack) in
                print(dataArray.count)
            }
    }
}

And then I just invoke the method SocketIOManager.connectSocket() in my ViewController. But the server produce the error. I don't develop the server side. I just need to know - did I create connection properly? How do you connect to socket through Socket.io these days?

P.S Server error - jwt must be provided (it seems like no token, but there is).

UPDATE (with dummy values):

I'm passing token like this:

static let manager = SocketManager(socketURL: URL(string: "https://myurl:443?token=\(token)")!)
static let socket = manager.defaultSocket
like image 843
Nastromo Avatar asked Dec 14 '22 17:12

Nastromo


2 Answers

It looks like you set the token in wrong place. According to the issue, token should be set as header parameter in configuration:

manager.config = SocketIOClientConfiguration(
    arrayLiteral: .compress, .connectParams(["Authorization": token])
)

Try to manage your token this way.

like image 121
pacification Avatar answered Dec 16 '22 06:12

pacification


So, to solve this issue we have to do a couple of actions:

  1. Add a .connectParams(["token": token]) for manager.config - in my case I have to use "token" key as URL parameter.
  2. Add a .secure(true) parameter for manager.config.
  3. Add an "App Transport Security Settings" key in info.plist (Dictionary type) and sub key "Allow Arbitrary Loads" (boolean type) with YES value.

CODE:

class SocketIOManager: NSObject {

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


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

    class func disconnectSocket(){
        socket.disconnect()
    }
}
like image 31
Nastromo Avatar answered Dec 16 '22 05:12

Nastromo