Using Socket For Real-time Chat

The socket.io is the framework that provides Real-time client-server communication In this article you will find some code in Swift (iOS) for implementing on the client-side and NodeJS for the backend.

Installing SocketIO in your project:

Lets, start with installing pods here’s the same method I am using for installing pod file of socket add pod ‘Socket. IO-Client-Swift’ in your pod file then go to the terminal and pod install after installing pod open your swift file where you need to use socket and import SocketIO.

How to Use Socket?

First you need to make constant Socket manager where you put socket url and make its config true and variable for SocketIOClient! like this.

let manager = SocketManager(socketURL: URL(string:“http://localhost:8080”)!, config: [.log(true), .compress])

var socket: SocketIOClient! = nil

after this, In viewDidLoad() you need to call these socket methods.

self.socket = manager.defaultSocket

self.setSocketEvents()

self.socket.connect()

private func setSocketEvents() {

self.socket.on(clientEvent: .connect) {data, ack in

print(“socket connected”)}

self.socket.on(“message”) {data, ack in

print(“received data: \(data)“)}}

for receiving the message call this method in viewDidLoad.

socket?.on(“receive-message”) {[weak self] data, ack in

if let msg = data[0] as? String {

print(“error”)}}

You can also call it a listening method. in this method, you can hit the API for getting updated data

for emitting Socket use this method on Action.

self. socket.emit(“send-message”, [ ])

References.

https://github.com/socketio/socket.io-client-swift

https://cocoapods.org/pods/Socket.swift

https://icreativesol.com/

William Clarke is a content consultant at iCreativeSOL, a pioneering digital marketing company in Austin.