9

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

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?

On the server side i cant even recognize a connection attempt. The variable serverURL is the same as i had before and

2 Answers 2

4

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.

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 } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @rambossa your tip for calling connect after adding handler saved my day :)
1

You should use SocketIOClient instance as class property.

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 Comment

well ok, i can do a new class and make everything a class method but how do i connect in the VC anyway? I tried your solution but it still wont even try to connect

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.