Created
May 1, 2019 14:46
-
-
Save koingdev/b2a7d7e489aa4e0913127f9993a1027d to your computer and use it in GitHub Desktop.
Network Listener (Detect network status changed and check Internet connection)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Reachability | |
final class NetworkListener { | |
private let notification = Notification.Name("NetworkListenerStatusDidChanged") | |
private let reachability: Reachability! | |
/// Return true if connected to Internet | |
private(set) var isConnected: Bool! | |
init() { | |
guard let safeReachability = Reachability() else { | |
reachability = Reachability() | |
return | |
} | |
reachability = safeReachability | |
// initialize connection state | |
isConnected = reachability.connection != .none | |
NotificationCenter.default.addObserver(forName: .reachabilityChanged, | |
object: nil, | |
queue: OperationQueue.main) { [weak self] notification in | |
guard let self = self else { return } | |
let newConnectionState = self.reachability.connection != .none | |
if self.isConnected != newConnectionState { | |
self.isConnected = newConnectionState | |
NotificationCenter.default.post(name: self.notification, object: nil) | |
} | |
} | |
do { | |
try reachability.startNotifier() | |
} catch { | |
dPrint("Could not start reachability notifier") | |
} | |
} | |
deinit { | |
NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: nil) | |
NotificationCenter.default.removeObserver(self, name: notification, object: nil) | |
} | |
/// Start monitoring network status changed | |
/// | |
/// - Parameter networkStatusDidChange: status changed callback | |
func observeNetworkStatusChanged(completion: @escaping (Bool) -> Void) { | |
NotificationCenter.default.addObserver(forName: notification, object: nil, queue: OperationQueue.main) { [weak self] notification in | |
guard let self = self else { return } | |
completion(self.isConnected) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As for now, I'm using this workaround: