Internet connection status swift reachability

2.8k views Asked by At

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

2

There are 2 answers

0
Shehata Gamal On BEST ANSWER

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)
1
Jiakan Wang On

For iOS12+, I would use NWPathMonitor which makes monitoring network change super easy:

import Network

let monitor = NWPathMonitor()

monitor.pathUpdateHandler = { path in
    if path.status != .satisfied {
        // Lost connection, do your thing here
    }
}
monitor.start(queue: DispatchQueue(label: "network_monitor"))

When you are done monitoring:

monitor.cancel()