[SOLVED] Implement socket.io-client in swift

Issue

I am trying to implement socket.io-client in swift. It is not working as supposed. I am unable to read any response from the server on my request. My socket is connecting but after that, I am unable to call events and getting their response.
Swift 4, Xcode 10

I am using a global class to declare socket functions as ‘clsGlobal’ and calling socket functions in different viewcontrollers.

import Foundation
import UIKit
import SocketIO

class clsSocket: NSObject {

let appdelegate = UIApplication.shared.delegate as! AppDelegate

static var manager = SocketManager(socketURL: URL(string: "my url")!, config: [.log(true), .reconnects(true)])
static var socket = manager.defaultSocket

static func ConnectSocket(){


    socket.connect()
    print(socket.status)

    socket.on("locationsUpdate", callback: { data,ack in
        print(data)
        let resp = data[0] as! Any
        print(resp)
    })
}
static func updateLocation(dId:NSNumber, uId:NSNumber, distance:Double){
    let datafield : [String:Any] = ["id":dId,
                                    "userid": uId,
                                    "travelledDistance":distance
    ]
    let data = try? JSONSerialization.data(withJSONObject: datafield)
    if socket.status == .connected {
        socket.emit("updateLocation",  data!)
        socket.emit("requestLocations")
    }

}
static func dogDisconnect(dogid:NSNumber, userid:NSNumber){
    let datafield = ["dId":did, "uId":userid]
    let dataobj = try? JSONSerialization.data(withJSONObject: datafield)
    socket.emit("disconnect",  dataobj!)
    socket.disconnect()
    socket.off("requestLocations")
}

}

How to know if the server is connected and how to print response from server?

Solution

I have created a Global for socket Class

import SocketIO

class SocketHelper {

    static let shared = SocketHelper()
    var socket: SocketIOClient!

    let manager = SocketManager(socketURL: URL(string: AppUrls.socketURL)!, config: [.log(true), .compress])

    private init() {
        socket = manager.defaultSocket
    }

    func connectSocket(completion: @escaping(Bool) -> () ) {
        disconnectSocket()
        socket.on(clientEvent: .connect) {[weak self] (data, ack) in
            print("socket connected")
            self?.socket.removeAllHandlers()
            completion(true)
        }
        socket.connect()
    }

    func disconnectSocket() {
        socket.removeAllHandlers()
        socket.disconnect()
        print("socket Disconnected")
    }

    func checkConnection() -> Bool {
        if socket.manager?.status == .connected {
            return true
        }
        return false

    }

    enum Events {

        case search

        var emitterName: String {
            switch self {
            case .searchTags:
                return "emt_search_tags"
            }
        }

        var listnerName: String {
            switch self {
            case .search:
                return "filtered_tags"
            }
        }

        func emit(params: [String : Any]) {
            SocketHelper.shared.socket.emit(emitterName, params)
        }

        func listen(completion: @escaping (Any) -> Void) {
            SocketHelper.shared.socket.on(listnerName) { (response, emitter) in
                completion(response)
            }
        }

        func off() {
            SocketHelper.shared.socket.off(listnerName)
        }
    }
}

How to use

Connect Socket using this code

SocketHelper.shared.connectSocket { (success) in

}

Start Listen event

SocketHelper.Events.search.listen { [weak self] (result) in
    // print(result[0])
}

Emit Event

SocketHelper.Events.search.emit(params: <--Your Params-->)

Answered By – Ronak Adeshara

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.