Reputation: 464
I am trying to integrate Socket in my app for real-time chat. Backend is done on node.js and frontend is developed on React and both are working fine.
I am having issue adding socket in my Swift Project.
In my aaHandlers()
function below, I expect to get a JSON response with detail of 4 users. Its working fine in Web app but not in Swift. Am I doing it right?
Here is the code
import Foundation
import SocketIO
let manager = SocketManager(socketURL: URL(string: "https://chatsapi.dummyUrl.io")!, config: [.log(true), .compress])
let socket = manager.defaultSocket
let socketConnectionStatus = socket.status
class SocketIOManager: NSObject {
static let sharedInstance = SocketIOManager()
override init() {
super.init()
}
func addHandlers() {
socket.on("get_all_user_list") { (data, ack) in
print("KK get_all_user_list", data,ack) // this line never gets called. I tried putting breakpoints.
}
}
func establishConnection() {
socket.connect()
}
func closeConnection() {
socket.disconnect()
}
}
P.S: Socket is connected.
Here is what I get in console:
> 2020-04-13 18:14:05.790193+0530 SocketTry[41289:9400138] LOG
> SocketIOClient{/}: Adding handler for event: get_all_user_list
Upvotes: 4
Views: 2697
Reputation: 1456
Please check if you using any authentication in the socket or not. If you are using authentication you need to set the configuration in your swift code. Here AUTHTOKEN which is user token you received from your login response from your server. AUTH_USER_ID which you received from your login response from your server.
class SocketIOManager: NSObject {
static let sharedInstance = SocketIOManager()
override init() {
super.init()
initialize()
}
func initialize() {
let socketUrl = "https://chatsapi.dummyUrl.io"
let specs: SocketIOClientConfiguration = [
.log(true),
.connectParams(getConnectionParam())]
socketManager = SocketManager(socketURL: URL(string: socketUrl)!, config: specs)
socket = socketManager?.defaultSocket
}
func getConnectionParam() -> [String: Any] {
return ["auth": "AUTHTOKEN", "user_id": "AUTH_USER_ID", "timeZone": "\(Date().localTimeZoneName)"]
}
func addHandlers() {
socket.on("get_all_user_list") { (data, ack) in
print("KK get_all_user_list", data,ack) // this line never gets called. I tried putting breakpoints.
}
}
func establishConnection() {
socket.connect()
}
func closeConnection() {
socket.disconnect()
}
}
Upvotes: 4
Reputation: 4570
Make sure you have established a connection to the server whenever the app becomes active.
func applicationDidBecomeActive(application: UIApplication) {
SocketIOManager.sharedInstance.establishConnection()
}
And one more thing An important notice: The above socket.on(...) method will be invoked automatically by the Socket.IO every time that the server sends the user list.
Upvotes: 0