WebSockets In Swift — IOS Development

WebSockets In Swift

What is WebSocket ? Why do we use it ? And why did I used an image of clock?

Well WebSocket is a communication protocol that follows stateful protocol and helps us to build Real Time Application (RTA) & thats why I used a clock image. A simple example for it is chat application. If you want to learn more about WebSocket please refer to my article where I’ve made a comparison between REST & WebSocket.

For this tutorial I am going to use a demo api you can get it from here. Enough of the theory lets move to practical implementation.

Practical Implementation For WebSocket In Swift :

In the code above we have created a UIButton and added it to the View & added the button target this button will help us to disconnect our WebSocket session. So on touchUpInside action our button will call the function closeSession() on line 34.

In the code above line 15 we created a global instance of URLSessionWebSocketTask. And we also inherited URLSessionWebSocketDelegate on line 3.

//Sessionlet session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue())

Line 37 we created a URLSession, Where configuration is default the delegate is self and delegateQueue is an OperationQueue we could use main queue as well but that is not something we should do.

//Server APIlet url = URL(string:  "wss://demo.piesocket.com/v3/channel_1?api_key=oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm&notify_self")

Line 40 is the url we got from here for demo purposes. But did you notice the WebSocket url is not using HTTP protocol instead it is using ‘WSS’ means websocket secure.

//SocketwebSocket = session.webSocketTask(with: url!)

Line 43 we created a WebSocket and passed in our URL.

//Connect and hanles handshakewebSocket?.resume()

Line 46 WebSocket.resume that will take care of our connections and handshakes.

func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {print("Connected to server")}

Line 65 we conformed to a protocol that is going to be called as soon as we open a connection.

func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {print("Disconnect from Server \(reason)")}

Line 69 we conformed to a protocol that is going to be called as soon as we close a connection.

//MARK: Receivefunc receive(){}//MARK: Sendfunc send(){}//MARK: Close Session@objc func closeSession(){}

Line 50 to 61 these are empty functions yet but let me explain what they will do. The function will listen for incoming messages whereas the send function will send messages to server and close function will disconnect us.

Let write our receive function first :

The receive function needs to be recurring so that we can keep on listening to the server response.

Line 9 we create a DispatchWorkItem if you are not familiar with it please read this article. Inside the workItem on line 11 we are calling the receive function of webSocket this function has a completion handler that returns a ‘Result’ containing message or error.

We created a Switch statement for the result on line 14 if its success then we get a message a message could be a data or string thats why we created a Switch on message too o n line 17. if it fails i.e on line 29 then we get the error. On line 33 we called the receive function again this will create the recurring feature for this function.

Line 36 we created a DispatchQueue that will triger after every 1 second and execute our workItem. This means our function will be called after every 1 second.

Now let me explain the send fucntion here again we created a workItem inside that workItem we called websocket send function this function will send message as ‘URLSessionWebSocketTask.Message’ this message could be a string or data here we are sending string and then we have a completion handler that will return us an error if there is a error we print the error on line 16 and if no error is occurred we call the send function again on line 14 this is just for testing purposes.

Line 22 we created a DispatchQueue that will triger after every 1 second and execute our workItem. This means our function will be called after every 1 second.

Let’s discuss about disconnecting from server now :

@objc func closeSession(){webSocket?.cancel(with: .goingAway, reason: "You've Closed The Connection".data(using: .utf8))}

This function get’s called when we press the button. The ‘.goingAway’ is the close code where as the reason is that you provide to user.

Where are we going to call all these three functions ???

The closeSession is already added as the target for the button we created earlier. Where as the send & receive will be called under the didOpenWithProtocol protocol.

Download the full source code HERE.

I hope I was able to explain well. If I did then please do follow me and share my article with your friends. This really motivates me to keep on wirtting.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store