Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect Socket in Swift 4

I want to connect my app to the socket here is the code :-

  import UIKit
  import SocketIO

 class SocketIOManager: NSObject {
static let manager = SocketManager(socketURL: URL(string: "myURL")!)
static let socket = manager.defaultSocket


class func connectSocket() {
    let token = UserDefaults.standard.getAccessToken()

    self.manager.config = SocketIOClientConfiguration(
        arrayLiteral: .connectParams(["token": token]), .secure(true) // problem is here in passing token value
        )
        socket.connect()
}

class func receiveMsg() {
    socket.on("new message here") { (dataArray, ack) in

        print(dataArray.count)

    }
}
}

I created a new class SocketIOManager.swift and I invoke my function in view controller

  SocketIOManager.connectSocket()

and I am not using the localhost url but still my app is not connected to the socket I think I followed this How to connect with Socket.io? Swift 4enter image description here and I also add App Transport Security in info.plist. Any help? The problem is when I am passing the token value it gives me error otherwise it is working properly. Should I need to pass token when using socket?

like image 410
viper Avatar asked Jan 29 '23 05:01

viper


2 Answers

Is your URL secured under HTTPS? If it is not, that could be the problem, due to App Transport Security restrictions.

See Info Plist Reference

See also this post here.

If that's not the problem. I'd suggest to check if your Socket version on both sides, server and client, are the same. Recently I had a problem because of that.

Hope it helps!

like image 41
alujan Avatar answered Feb 06 '23 07:02

alujan


You should make a shared property in your SocketIOManager class like this:

static let shared = SocketIOManager()

and then create init() like this:

    var socket: SocketIOClient!

    // defaultNamespaceSocket and swiftSocket both share a single connection to the server
    let manager = SocketManager(socketURL: URL(string: "http://localhost:3000")!, config: [.log(true), .compress])

    override init() {
        super.init()

        socket = manager.defaultSocket
        }

and finally write your methods like this:

func connectSocket() {
    let token = UserDefaults.standard.getAccessToken()

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

func receiveMsg() {
    socket.on("new message here") { (dataArray, ack) in

        print(dataArray.count)

    }
}

and call your method like this:

SocketIOManager.shared.connectSocket()

The point is that you should make a strong reference to manager property in your viewController and static let shared = SocketIOManager() you do this for you!

like image 97
Seyed Samad Gholamzadeh Avatar answered Feb 06 '23 09:02

Seyed Samad Gholamzadeh