I'm using socket.io to use the real-time mechanism. Problem that I'm facing right now is that Socket.io's object created after the viewController is loaded
I'm using Singleton design
import SocketIO
class SocketIOManager: NSObject {
static let sharedInstance = SocketIOManager()
var socket: SocketIOClient!
func establishConnection() {
socket = SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])
socket.connect()
}
func closeConnection() {
socket.disconnect()
}
}
I need to set the socket in the establishConnection no matter what to make sure that user has establish the connection to the server together with the token. If I follow Vlad's answer, the connection will be never be established because the token is empty before hand thus user won't get connected.
User logs in
func logIn() {
// Getting it from alamofire
keychain["token"] = token
//then only establish connection
SocketIOManager.sharedInstance.establishConnection()
}
If I use Init method then the socket will be nil because in the applicationDidBecomeActive there's the SocketIOManager.sharedInstance.establishConnection(), so the logic is whenever user loads up the app the applicationDidBecomeActive will run
so technically I'm using sharedInstance to run the socket.io object.
func applicationDidBecomeActive(_ application: UIApplication) {
SocketIOManager.sharedInstance.establishConnection()
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
Right now the socket object in the didBecomeActive runs after the view loaded
override func viewDidLoad() {
super.viewDidLoad()
listeningOnMerchant()
}
func listeningOnMerchant() {
// I got error around here
SocketIOManager.sharedInstance.socket.on("listening") { ack, data in
print("something")
}
}
}
Which will crash because socket is nil. How do I make the viewController not crash. I could use the let method to stop the crash
if let socket = SocketIOManager.sharedInstance.socket {
}
But it will be nil if I use socket and socket won't be running. How do I not make the socket not crash?
Because i really need to put the socket.connect on applicationDidBecomeActive to make it consistent as in the connection vs didLaunch
Thanks!