Search code examples
iosswiftnsurlsession

How to check when the network is unavailable in iOS 13?


I have added some logic to handle the network is not unavailable but I have a hard time to trigger the error handler. I am using URLError networkUnavailableReason is it the right one?

DataService.shared.GetMyData(completion: {(result) in
    DispatchQueue.main.async {
        switch result {
            case .success(let data):


                break
            case .failure(let error):
                print(error)
                if let error = error as? URLError, error.networkUnavailableReason == .constrained  {

                    self.showAlert()
                }

                break;
        }
    }
})

Solution

  • You can use NWPathMonitor, which is a network monitor, to check if the network is available. I used one like this, by creating a struct for it :

    // make sure to import Network in your file when you do this
    struct NetworkMonitor {
        static let monitor = NWPathMonitor()
        static var connection = true
    }
    

    Then used it like this, wherever you want to start monitoring:

    NetworkMonitor.monitor.pathUpdateHandler = { path in
                   if path.status == .satisfied {
                        print("connection successful")
                        NetworkMonitor.connection = true
                        // then respond to successful connection here, I used a notification and this connection bool
                  } else {
                        print("no connection")
                        NetworkMonitor.connection = false
                        // respond to lack of connection here
                   }
              }
    
              let queue = DispatchQueue(label: "Monitor")
              NetworkMonitor.monitor.start(queue: queue)