我正在尝试在用户加入聊天室时发出一个事件。所以我有两个班级:
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执行发射?
答案 0 :(得分:0)
在调用emit之前,套接字需要连接。为此,Socket.IO有一个监听器socket.on(" connect")。因此,在我们连接状态后,我们可以发出。
socket.on("connect") { _, _ in
print("socket connected")
socket.emit("your_event", jsonObject)
}