I am working with iOS 8 and Swift. I want to use the official socket.io client but for some reason it does not attempt to connect. I followed the example given here: https://github.com/socketio/socket.io-client-swift
我正在使用iOS 8和Swift。我想使用官方socket.io客户端,但由于某种原因它不会尝试连接。我按照这里给出的例子:https://github.com/socketio/socket.io-client-swift
let socket = SocketIOClient(socketURL: "\(CurrentConfiguration.serverURL)")
socket.reconnects = true
socket.reconnectWait = 10
socket.nsp = "/messagelist"
// Connect
socket.connect()
socket.onAny {println("got event: \($0.event) with items \($0.items)")}
socket.on("connect") {data, ack in
println("socket connected")
}
socket.on("error") {data in
println("socket ERROR")
println(data)
}
Can anyone confirm this? Is this a version problem or maybe related to Swift 1.2?
谁能证实这一点?这是版本问题还是与Swift 1.2有关?
On the server side i cant even recognize a connection attempt. The variable serverURL is the same as i had before and
在服务器端,我甚至无法识别连接尝试。变量serverURL与之前的变量相同
2 个解决方案
#1
3
Make sure to call socket.connect()
after you call your handlers. A good practice would be to create a function with all of your required handlers, and call it in the viewDidLoad
method. Aftewards you would then call the connect method.
确保在调用处理程序后调用socket.connect()。一个好的做法是使用所有必需的处理程序创建一个函数,并在viewDidLoad方法中调用它。然后,您将调用connect方法。
Example:
例:
let socket = SocketIOClient(socketURL: "URL")
override func viewDidLoad() {
super.viewDidLoad()
// socket.io
addHandlers()
socket.connect()
}
func addHandlers() {
self.socket.onAny {println("Got event: \($0.event), with items: \($0.items)")}
self.socket.on("processReq") {[weak self] data, ack in
// handler code here
}
}
#2
1
You should use SocketIOClient instance as class property.
您应该使用SocketIOClient实例作为类属性。
class aClass {
let socket = SocketIOClient(socketURL: url)
func someFunction() {
socket.on("connect") {data, ack in
println("socket connected")
}
}
}
I think it's because there's lots of closures used in it.
我认为这是因为它中使用了大量的闭包。
#1
3
Make sure to call socket.connect()
after you call your handlers. A good practice would be to create a function with all of your required handlers, and call it in the viewDidLoad
method. Aftewards you would then call the connect method.
确保在调用处理程序后调用socket.connect()。一个好的做法是使用所有必需的处理程序创建一个函数,并在viewDidLoad方法中调用它。然后,您将调用connect方法。
Example:
例:
let socket = SocketIOClient(socketURL: "URL")
override func viewDidLoad() {
super.viewDidLoad()
// socket.io
addHandlers()
socket.connect()
}
func addHandlers() {
self.socket.onAny {println("Got event: \($0.event), with items: \($0.items)")}
self.socket.on("processReq") {[weak self] data, ack in
// handler code here
}
}
#2
1
You should use SocketIOClient instance as class property.
您应该使用SocketIOClient实例作为类属性。
class aClass {
let socket = SocketIOClient(socketURL: url)
func someFunction() {
socket.on("connect") {data, ack in
println("socket connected")
}
}
}
I think it's because there's lots of closures used in it.
我认为这是因为它中使用了大量的闭包。