Skip to content

Commit c45629e

Browse files
committed
Fix autoreconnect
The reachability object was was not being retained, so it was being deallocated right after being created. This also stops the autoreconnect behavior if the connection is explicitly disconnected.
1 parent 7d6bcc5 commit c45629e

File tree

1 file changed

+19
-21
lines changed

1 file changed

+19
-21
lines changed

Source/PusherSwift.swift

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,19 @@ public class PusherConnection: WebSocketDelegate {
161161
public var channels = PusherChannels()
162162
public var socket: WebSocket!
163163
public var URLSession: NSURLSession
164+
165+
public lazy var reachability: Reachability? = {
166+
let reachability = try? Reachability.reachabilityForInternetConnection()
167+
reachability?.whenReachable = { [unowned self] reachability in
168+
if !self.connected {
169+
self.socket.connect()
170+
}
171+
}
172+
reachability?.whenUnreachable = { [unowned self] reachability in
173+
print("Network unreachable")
174+
}
175+
return reachability
176+
}()
164177

165178
public init(key: String, socket: WebSocket, url: String, options: PusherClientOptions, URLSession: NSURLSession = NSURLSession.sharedSession()) {
166179
self.url = url
@@ -225,15 +238,19 @@ public class PusherConnection: WebSocketDelegate {
225238

226239
public func disconnect() {
227240
if self.connected {
241+
self.reachability?.stopNotifier()
228242
self.socket.disconnect()
229243
}
230244
}
231-
245+
232246
public func connect() {
233247
if self.connected {
234248
return
235249
} else {
236250
self.socket.connect()
251+
if let reconnect = self.options.autoReconnect where reconnect {
252+
_ = try? reachability?.startNotifier()
253+
}
237254
}
238255
}
239256

@@ -529,30 +546,11 @@ public class PusherConnection: WebSocketDelegate {
529546
if let error = error {
530547
print("Websocket is disconnected: \(error.localizedDescription)")
531548
}
532-
549+
533550
self.connected = false
534551
for (_, channel) in self.channels.channels {
535552
channel.subscribed = false
536553
}
537-
538-
if let reconnect = self.options.autoReconnect where reconnect {
539-
let reachability = try! Reachability.reachabilityForInternetConnection()
540-
541-
if let reachability = try? Reachability.reachabilityForInternetConnection() {
542-
543-
reachability.whenReachable = { reachability in
544-
if !self.connected {
545-
self.socket.connect()
546-
}
547-
}
548-
549-
reachability.whenUnreachable = { reachability in
550-
print("Network unreachable")
551-
}
552-
}
553-
554-
if let _ = try? reachability.startNotifier() {}
555-
}
556554
}
557555

558556
public func websocketDidConnect(ws: WebSocket) {}

0 commit comments

Comments
 (0)