如何正确使用socket.io-client-swift

3

我在互联网上寻找一个合适的例子,以便在iOS上使用Socket.IO(实际上是在客户端上使用socket.io-client-swift),并提供清晰的编码示例。有谁能帮助我吗?


这会有所帮助:https://github.com/socketio/socket.io-client-swift - Faysal Ahmed
以下是使用 socket.io 制作聊天应用的教程链接:https://www.appcoda.com/socket-io-chat-app/ - Faysal Ahmed
感谢 @FaysalAhmed - Bhashitha Hemantha
1个回答

1
这是一个 Socket.io 客户端的示例。
import SocketIO    
class soket {
    var lat = ""
    var lng = ""
    let appDelegate = UIApplication.shared.delegate as!AppDelegate
    init(lat: String, lng: String) {
        self.lat = lat
        self.lng = lng
    }
    func connect()  {
        print("llamada al socket")
        print(contantes.init().addres)
        let socket = SocketIOClient(socketURL: URL(string: contantes.init().addres)!,config: [.connectParams(["accessToken" : appDelegate.token]),.forcePolling(true),.nsp("/vendedor"), .log(true)])
        let myJSON = [
            "lng":lng,
            "lat":lat,
            "idvendedor":appDelegate.idSeller
        ]
        socket.on("connect") {data, ack in
            print("socket connected")
            socket.emit("setLocation",myJSON)
            print("Mostrando el Json: \(myJSON)")
        }
        socket.on("locationChanged", callback: {_,_ in
            print("disconnected")
            socket.disconnect()
        })
        socket.connect()
    }
}

这个类是一个简单的套接字,用于向服务器报告设备位置,在这种情况下,服务器端使用命名空间,因此套接字必须加入它以发送数据。以下是在viewController中调用它的代码。
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        let sok = soket(lat: String(location.coordinate.latitude),lng:String(location.coordinate.longitude))
        sok.connect()
        locationManager.stopUpdatingLocation()
    }
}

套接字背后的主要概念是配置处理程序以侦听或发射来自服务器的数据并建立连接。这里有另一个例子在iOS Swift中集成Socket.IO客户端

谢谢。您能解释一下这行代码中的参数吗?'let socket = SocketIOClient(socketURL: URL(string: contantes.init().addres)!,config: [.connectParams(["accessToken" : appDelegate.token]),.forcePolling(true),.nsp("/vendedor"), .log(true)])' - Bhashitha Hemantha
这些参数是特定于我的后端连接的,但是soketURL中的后端URL和config中的数组包含了后端所需的内容,例如访问令牌。force polling用于启用websokect,nsp用于加入可能需要的命名空间,log用于在xcode中显示日志。 - Yoel Jimenez del valle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接