Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement socket.io-client in swift

Tags:

swift

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?

like image 830
Rj19 Avatar asked May 11 '26 22:05

Rj19


2 Answers

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-->)
like image 82
Ronak Adeshara Avatar answered May 13 '26 10:05

Ronak Adeshara


Please remember that the socketio client in swift is not yet compatible with js socket.io version 3.x.x (as of 1/21/2021).

This was an issue we came across since we were using the latest socketio version in our node server (3.1.0). The client will be able to initially connect but will not be able to receive any messages emitted from the server.

We solved our problem by downgrading our server to socketio version 2.4.1

like image 21
Farbod Nowzad Avatar answered May 13 '26 10:05

Farbod Nowzad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!