gpt4 book ai didi

ios - 如何在 Socket.io Swift4 中发出事件

转载 作者:行者123 更新时间:2023-11-30 11:38:14 25 4
gpt4 key购买 nike

我试图在用户加入聊天室时发出一个事件。所以我有两门课:

  • SocketIOManager
  • View Controller

SocketIOManager代码:

import SocketIO

class SocketIOManager: NSObject {

static let manager = SocketManager(socketURL: URL(string: "https://myurl.com:443")!, config: [.log(true), .compress])
static let socket = manager.defaultSocket

class func connectSocket(){
self.manager.config = SocketIOClientConfiguration(
arrayLiteral: .connectParams(["token": myToken), .secure(true)
)
socket.connect()
}

class func connectToChatRoom(chat: String, user: String){
let jsonDic = ["chat": chat,
"user": user]

print("CHEKING SOCKET CONNECTION 1-ST TIME - \(socket.status)") // This gives me - connecting

socket.emit("join", jsonData)

print("CHEKING SOCKET CONNECTION 2-ND TIME - \(socket.status)") // This gives me - connecting
}

class func isSocketConnected() -> Bool{
if socket.status == .connected {
return true
}
return false
}
}

在我的ViewController中,我这样做 - 首先我连接套接字。然后我尝试发出。

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

SocketIOManager.connectSocket()
SocketIOManager.connectToChatRoom(chat: chatID, user: myID)

print("\(SocketIOManager.isSocketConnected())") //This gives me "false"
}
}

毕竟我在 Socket.IO 的日志中收到错误:未连接时尝试发出连接

CHEKING SOCKET CONNECTION 1-ST TIME - connecting
2018-03-27 12:26:04.895072+0300 MyApp[3760:1940922] LOG SocketIOClient{/}: Handling event: error with data: ["Tried emitting join when not connected"]
CHEKING SOCKET CONNECTION 2-ND TIME - connecting
false

我的排放正确吗?如何使用 Socket.IO 执行发射?

最佳答案

在调用emit 之前,套接字需要连接。为此,Socket.IO 有一个监听器 socket.on(“连接”)。因此,在我们获得连接状态后,我们就可以发出信号。

socket.on("connect") { _, _ in
print("socket connected")
socket.emit("your_event", jsonObject)
}

关于ios - 如何在 Socket.io Swift4 中发出事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49510003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com