You can observe reachability changes using standard NotificationCenter observers. Note: All notifications are delivered on the main queue.
- Observe the
.reachabilityChanged notification. - Call
startNotifier() to begin. - Use
stopNotifier() and removeObserver to clean up.
The notification object is the Reachability instance itself, which contains the current connection state.
// declare this property where it won't go out of scope relative to your listener
let reachability = try! Reachability()
// Inside viewWillAppear or similar:
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
do {
try reachability.startNotifier()
} catch {
print("could not start reachability notifier")
}
@objc func reachabilityChanged(note: Notification) {
let reachability = note.object as! Reachability
switch reachability.connection {
case .wifi:
print("Reachable via WiFi")
case .cellular:
print("Reachable via Cellular")
case .unavailable:
print("Network not reachable")
}
}
// To stop notifications:
reachability.stopNotifier()
NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)