简体   繁体   中英

Internet connection status swift reachability

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)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM