Async completion blocks with singleton class swift
<p>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.</p>

<p>What is an nice and proper way to solve this?</p>

<pre><code>   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: (() -&gt; Void)!) {
             if(!connectionMade){
                  socket.connect()
                  connectionMade = true;
              }

            completionHandler();
        }

        func connectToRoom(roomNumber: String){
            establishConnection { 
                self.socket.emit("connectToRoom", roomNumber);
            }
        }
    }
</code></pre>

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

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

<pre><code>  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 {

            }
  }
</code></pre>

<p>And this at my view controller:</p>

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

        }
</code></pre>

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

<pre><code>SocketIOManager.sharedInstance.connectToRoom(self.roomNumber);
</code></pre>

<p>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.</p>