Skip to content

Commit ba29d4e

Browse files
psycotica0Michelle Ellis
authored andcommitted
Reconnect on Disconnect Unless Reachability Changes
If the app is allowed to go to sleep in the background, or perhaps even if the websocket is just closed from the remote end, it will never reconnect. We're currently relying on the reachability to tell us when it's time to connect again, but that's assuming that the reason we disconnected was reachability. That's not always the case. So, I've started a timer on disconnect that gives reachability 1 second to figure itself out before we try to reconnect. We cancel the operation if reachability changes, otherwise we let it run.
1 parent de707bc commit ba29d4e

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

Source/PusherConnection.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,18 @@ public class PusherConnection {
1717
public var socket: WebSocket!
1818
public var URLSession: NSURLSession
1919
public weak var stateChangeDelegate: ConnectionStateChangeDelegate?
20+
internal var reconnectOperation: NSOperation?
2021

2122
public lazy var reachability: Reachability? = {
2223
let reachability = try? Reachability.reachabilityForInternetConnection()
2324
reachability?.whenReachable = { [unowned self] reachability in
25+
self.reconnectOperation?.cancel()
2426
if self.connectionState == .Disconnected {
2527
self.socket.connect()
2628
}
2729
}
2830
reachability?.whenUnreachable = { [unowned self] reachability in
31+
self.reconnectOperation?.cancel()
2932
print("Network unreachable")
3033
}
3134
return reachability

Source/PusherWebsocketDelegate.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,17 @@ extension PusherConnection: WebSocketDelegate {
3939
for (_, channel) in self.channels.channels {
4040
channel.subscribed = false
4141
}
42+
43+
let operation = NSBlockOperation {
44+
self.socket.connect()
45+
}
46+
47+
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC)), dispatch_get_main_queue()) {
48+
NSOperationQueue.mainQueue().addOperation(operation)
49+
}
50+
51+
self.reconnectOperation?.cancel()
52+
self.reconnectOperation = operation
4253
}
4354

4455
public func websocketDidConnect(ws: WebSocket) {}

0 commit comments

Comments
 (0)