iosswiftuialertviewsemaphorecocoaasyncsocket

Swift: Show UIAlert while waiting for semaphore


I'm using CocoaAsyncSocket pod to transfer data from measurement instrument to an iOS device. The transfer works pretty well, but I get in trouble, if I have to switch between different mobile instruments.

If I need to change the instrument / connect to another instrument, I have to wait for some events:

  1. I have to be sure to be disconnected. This is typically done by waiting for public func socketDidDisconnect(...) included in the GCDAsyncSocketDelegate
  2. I have to connect to the other instrument. If it is still the tcp interface, I have to wait for public func socketDidConnectToHost(...)

So there are two operations which take some time. Because there is no valid connection, the user just can wait. To inform the user what's going on, I would like to present an UIAlert until the mentioned events are finished. How can I achieve this?


Solution

  • Semaphores seem way too low level for your case, unless you are doing it for educational purposes.

    Using NotificationCenter instead:

    1) Post a "didDisconnectNotification" (string name being arbitrary) from socketDidDisconnect(...) and in it's corresponding handler update your viewController UI indicating the user a connectivity problem.
    2) Post a "didConnectNotification" from socketDidConnectToHost(...) and in it's handler (distinct from 1) dismiss the connectivity problem indicator^.

    Note: On your viewController first appearance you would probably start with 2) so there's nothing yet to dismiss.

    You can find numerous examples related to NotificationCenter on SO: https://stackoverflow.com/a/24756761/5329717

    In a scenario where the two aforementioned operations are independent (i.e. they can occur in any order relative to each other) the GCD mechanism to use would be DispatchGroup. It's somewhat closer to your attempt at using a semaphore, however you don't need it either because your 2 events (disconnect & connect) are dependent (i.e. their respective order of occurence is fixed).
    An example valid usage case of DispatchGroup would be synchronising responses of many image fetch requests when you don't care about their order of arriving (you either get all of them or do not proceed).