Implementation of Socket in Swift

Deeksha Sharma
4 min readNov 21, 2020

iOS apps exist in millions out there, and most of them communicate with servers to exchange data. In their majority, the server implements and provides RESTful APIs that apps can use for the communication. When an app needs to send data to the server, or fetch from it, it makes the proper request and after a while the data has been returned. That happens several times during the app runtime period.

The above covers the most use cases, but not all. What if, for example, an app should show some sort of a news feed that needs to be updated all the time? Or what if real-time conversation between users should be supported as an app feature?

Thankfully, there’s a better solution when it’s necessary to receive data from a server instantly (every time such data becomes available), and without having the app to send any request to the server at all. That solution is based on making use of websockets, and it totally erases the couple aforementioned issues. You can find a couple of interesting topics about websockets here and here, but also feel free to search the web for additional information.

The websocket communication relies on the client-server logic, where a persistent connection between a server and a client always exists. To be more precise, the server “opens” a dedicated port where clients get connected to it. Once that happens, all the connected apps can send messages to that port (outgoing messages), and listen to it for any incoming messages. And as that’s the default behaviour when connecting to sockets, every connected client to a server will automatically get its messages without any additional request at all. Most importantly, when a message is sent to that port by a server, the recipient clients will instantly receive it, so they can take any further actions (like updating a news feed for example) immediately.

Implementing the connection to a socket and communicating through it with a server is not the easiest task on the world. Even though the whole idea sounds fascinating, there might exist several problems until it’s possible to achieve a proper communication. Thankfully (once again), here it comes into the play a really handful framework that takes charge of all the connection issues behind the scenes, and makes the socket-based communication a real piece of cake. It’s called Socket.IO.

It's based on handshake mode. First need to send request to server then server send acknowledgment back only then will send data.

Swift Implementation:

First need to install pods:
pod ‘Socket.IO-Client-Swift’

Establish Connection:

let manager = SocketManager(socketURL: URL(string: “Enter your Url here”)!)

//Establish a connection with socket
class func establishConnection() {
socket.on(clientEvent: .connect) {data, ack in
print(“socket connected”)
//Call your first socket here
}
socket.connect()
}

Call establishConnection in an appdelegate class in didFinishLaunchingWithOptions method. In socket basically we need to use emit to send data to server and listen to receive data from server.

For emitting(sending) a data first need to create a dictionary and then send data to server over a particular end point .

let dict = [“driverId”: ””,
“bookingId”: ” ”,
“authToken”: ” ”]
print(dict)
WebSocketManager.socket.emit(“your socket end point”, with: [dict])

For listening (receiving) a data from server need to use .on request and save data in array for further use.Listen data from server on same end point in which earlier you sent it to server.

WebSocketManager.socket.on(“your socket end point”) { (dataArray, SocketAck) in
if
let data = dataArray[0] as? [String:Any]
print(“^^^^^^^^^^”,data)
if let status = data[“success”]as?Int {
if(status == 1){
completion(true)
}else{
completion(false)
}}
}}

Off socket when you will leave particular controller . Otherwise it will stay in memory and increase memory usage continually also causes a crashes in small devices.

override func viewDidDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
WebSocketManager.socket.off(“your socket end point”)
}

Summary:

Keep in mind that Socket.IO doesn’t consist of a “super-weapon” that is suitable for all kinds of tasks, and it cannot replace traditional ways to communicate with servers. However, you just saw that it’s a wonderful tool for specific cases, and in my opinion your best option when you need real-time solutions. Anyway, I hope you’ve found what you read useful, and that you’ve learnt something new. Moreover, I hope that you’ve enjoyed reading this text as much as I have during its writing.

--

--

Deeksha Sharma

I am an iOS developer having an experience in objective c and swift.