How to solve strange behavior Reachability.swift in simulator?

394 Views Asked by At

I am using Reachability.swift to monitor the connection. However, the answer always comes with a delay of 1 step .Below is the code snippet:

override func viewWillAppear(_ animated: Bool) {
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged(note:)), name: .reachabilityChanged, object: self.reachability)
            do{
                try self.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")
  }
}

When I run the application - I get "Reachable via WiFi"

When I disconnect the connection - I do not get anything, although I expect to receive: "Network not reachable"

And when I turn the connection back on, I expect to get: "Reachable via WiFi", but I get: "Network not reachable"

It seems that I receive messages with a delay of 1 step, what's wrong?

p.s. Only simulator has this problem, but it works well on the device.

0

There are 0 best solutions below