nuclearace / Socket.IO-Client-Swift

socket.io-client for Swift
Other
361 stars 53 forks source link

Getting Nil on socket. #146

Open kacak9229 opened 6 years ago

kacak9229 commented 6 years ago

I'm building a socket.io sort of a real time chat and currently I'm facing an inconsistency problem

My goal is that whenever user removes the app and join the app again, then socket.io will work, this has something to do with the app delegate

The two states that I'm using to establish the connection

func applicationDidEnterBackground(_ application: UIApplication) {
          SocketIOManager.sharedInstance.closeConnection()
          // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
          // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
      }

      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.
      }

Before Swift 3.2 it works perfectly but now I've been getting crashes/error because socket.io is not created beforehand

I'm using Singleton design

import SocketIO

 class SocketIOManager: NSObject {

     static let sharedInstance = SocketIOManager()

     var socket: SocketIOClient!

     func establishConnection() {
        socket.connect()

     }

     func closeConnection() {
         socket.disconnect()
     }

 }

On the ViewController I'm running a basic socket.io.on, I received an error because socket is nil

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        listeningOnMerchant()

    }

    func listeningOnMerchant() {
       // I got error around here
       SocketIOManager.sharedInstance.socket.on("listening") { ack, data in
          print("something")

       }
    }
}

ViewController is the initial view controller whenever a user loads up his app. I got error at this position SocketIOManager.sharedInstance.socket.on("listening") seems like socket hasn't yet been created yet.

I tried to put it on didFinishLaunch on AppDelegate, it removes the crashes but if user pauses his app then it won't get connected.

What should I do to fix this problem.

Regards