Skip to content

Instantly share code, notes, and snippets.

@koingdev
Created May 1, 2019 14:46
Show Gist options
  • Save koingdev/b2a7d7e489aa4e0913127f9993a1027d to your computer and use it in GitHub Desktop.
Save koingdev/b2a7d7e489aa4e0913127f9993a1027d to your computer and use it in GitHub Desktop.
Network Listener (Detect network status changed and check Internet connection)
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)
}
}
}
@hans-min
Copy link

hans-min commented Feb 8, 2022

As for now, I'm using this workaround:

class ViewController: UIViewController {
    let r = NetworkMonitor.shared
    @IBOutlet var internet: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        switch r.isConnected{
        case true:
            self.internet.tintColor = .green
        case false:
            self.internet.tintColor = .red
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        r.observeNetworkStatusChanged{ status in
            switch status{
            case true:
                self.internet.tintColor = .green
            case false:
                self.internet.tintColor = .red
            }
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment