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 4 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?
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!
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With