我想在有套接字连接时执行一个函数。但是当有连接时,可以立即触发方法。必须在没有连接时建立连接。
解决这个问题的好方法是什么?
import SocketIO
class SocketIOManager: NSObject {
static let sharedInstance = SocketIOManager()
var socket: SocketIOClient = SocketIOClient(socketURL: NSURL(string: "http://192.168.1.59:3000")! as URL)
var connectionMade = false;
override init() {
super.init()
}
func establishConnection(completionHandler: (() -> Void)!) {
if(!connectionMade){
socket.connect()
connectionMade = true;
}
completionHandler();
}
func connectToRoom(roomNumber: String){
establishConnection {
self.socket.emit("connectToRoom", roomNumber);
}
}
}
这是一个很好的设置吗?是的,我必须在连接关闭时将bool设置为false:)
我问这个是因为我的代码有问题。我在应用代表处打电话给这个连接:
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
SocketIOManager.sharedInstance.establishConnection {
}
}
这是我的视线控制器:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
SocketIOManager.sharedInstance.connectToRoom(self.roomNumber);
}
但服务器永远不会收到connectToRoom'消息'。当我按下带有此代码的按钮时,它可以工作:
SocketIOManager.sharedInstance.connectToRoom(self.roomNumber);
因此看起来套接字连接不是在viewdidload上进行的。但是当我按下按钮时为什么会起作用呢?因为我正在等待来自SocketIOManger类连接的connectTo Room函数的回调。
答案 0 :(得分:0)
只需在连接上添加一个监听器,如下所示:
socket.on(clientEvent: .connect) { [unowned self] data, ack in
print("socket connected")
print(data)
if !self.HasConnected {
// JOIN YOUR ROOM
self.HasConnected = true
}
}