Async completion blocks with singleton class swift

446 Views Asked by At

I want to execute a function when there is an socket connection. But the methods can be fired immediately when there is an connection. The connection must be made when there isn't one.

What is an nice and proper way to solve this?

   import SocketIO

    class SocketIOManager: NSObject {
        static let sharedInstance = SocketIOManager()
        var socket: SocketIOClient = SocketIOClient(socketURL: NSURL(string: "http://192.168.1.59:3000")! as URL)
        var connectionMade = false;


        override init() {
            super.init()
        }

        func establishConnection(completionHandler: (() -> Void)!) {
             if(!connectionMade){
                  socket.connect()
                  connectionMade = true;
              }

            completionHandler();
        }

        func connectToRoom(roomNumber: String){
            establishConnection { 
                self.socket.emit("connectToRoom", roomNumber);
            }
        }
    }

Is this an good setup? And yes I have to set the bool to false when the connection is closed:)

I ask this because I have a problem with my code. I call this at the app delegate to made an connection:

  func applicationDidBecomeActive(_ application: UIApplication) {
            // 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.

            SocketIOManager.sharedInstance.establishConnection {

            }
  }

And this at my view controller:

  override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
         SocketIOManager.sharedInstance.connectToRoom(self.roomNumber);

        }

But the server is never getting the connectToRoom 'message'. It works when I push on a button with this code in it:

SocketIOManager.sharedInstance.connectToRoom(self.roomNumber);

So it looks like the socket connection isnt made at the viewdidload. But why does it work when I push the button? Because i'm waiting for an callback at the at the connectTo Room function from the connection at the SocketIOManger class.

1

There are 1 best solutions below

0
On

just add a listener on connect like below:

socket.on(clientEvent: .connect) { [unowned self] data, ack in
            print("socket connected")
            print(data)
            if !self.HasConnected {
                // JOIN YOUR ROOM
                self.HasConnected = true
            }
        }