I have the following code to determine whether if there is an internet connection or no. This code works fine. How Can I know if I suddenly lost the connection
var reachability:Reachability?
reachability = Reachability()
self.reachability = Reachability.init()
if((self.reachability!.connection) != .none)
{
print("Internet available")
}
Does reachability class has a feature that reports if the connection is broken. If there is no way to handle that issue with reachability what is the other option
Declare this in AppDelegate / Vc
let reachability = Reachability()!
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}
//
when status is changed this method is called
@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 .none:
print("Network not reachable")
}
}
//
to avoid crashes don't forget to un register
reachability.stopNotifier()
NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)