How to connect with Socket.io? Swift 4

2020-07-17 05:29发布

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

2条回答
爷、活的狠高调
2楼-- · 2020-07-17 06:07

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.

查看更多
家丑人穷心不美
3楼-- · 2020-07-17 06:09

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()
    }
}
查看更多
登录 后发表回答