iosobjective-cwebsocketsocketrocket

iOS - Best solution for implementing websocket connection across the entire iOS app?


In my app, websocket connection and communication is in the certain ViewController but later came request to receive messages through websocket across the entire app.

What would be the best way to do it? To move the websocket code to AppDelegate or to create super ViewController? Or something else and better?


Solution

  • If the requirement is for your app to be communicating with an external party at all times and that multiple view controllers can present and act on messages, then you need to move the communication out to a separate instance and provide an interface for your view controllers to interact with it.

    I would create a communication class or set of classes which you can create a shared instance of within your appDelegate. Different view controllers can then access this shared instance via the appDelegate or some other mechanism you provide.

    How complex this will have to be depends on your exact requirement.

    Edit following comment updating requirement:

    The requirement seems to be you want to be able to receive messages all the time, regardless of the view controller but be able to post messages via the view controller.

    To do this you want to have your shared instance provide an API for openeing connections. Have it register the web socket (s) (not sure which web socket API you are using) which are connected on the runloop so that you can deal with communication when there is activity and do other things when there is no activity. You can do this on the main thread or a background thread, its all down to how much load you think messaging will add.

    Have your new shared instance handle all incoming messages and put them in an internal queue. Provide a subscription interface for client instances (like your view controllers) to register for incoming message notification. You can make this a direct interface or use notifications. Your choice depending on the use case. If view controllers can go back in time, then you need to provide access to the full set of messages received and sent in the past. A policy for clearing these out or caching to file will be required unless messages are short lived and you store no history.

    For sending messages, provide an API in the shared instance which allows a message to be queued for sending with a future acknowledgement. Use the run loop mechanisms for being notified when a socket is ready for write to send the message. Provide a message sent acknowledgement back to the sending UI so the UI is not blocked waiting to send and to allow other messages to be written while the first is pending.

    There is quite a bit of work here for you to do.