How to check Internet connection in Swift


Greetings, traveler!

If your app is highly bound to a network connection, informing the user if the connection is lost will be a nice decision.

You can do it via Apple’s framework called Network. To monitor and react to network changes, you can use the NWPathMonitor class. For convenience, we will create a wrapper for it.

We will create a class that holds an instance of NWPathMonitor. To start monitoring, we will create a function with completion, which we will use to provide data outside. You can use NWPath.Status or just a Bool value — that depends on your needs. Here, we will use a Bool value to simplify the code.

import Network

final class NetworkMonitor {

    private let monitor = NWPathMonitor()
    private let queue = DispatchQueue(label: "network-monitor")
    
    func startMonitoring(_ completion: @escaping (Bool) -> Void) {
        monitor.pathUpdateHandler = { path in
            DispatchQueue.main.async {
                completion(path.status == .satisfied)
            }
        }
        
        monitor.start(queue: queue)
    }
    
}

To stop monitoring, you can use a cancel() method.

func stopMonitoring() {
    monitor.cancel()
}

You can use a NWPathMonitor currentPath variable to fetch the current status value.

var isNetworkAvailable: Bool {
    monitor.currentPath.status == .satisfied
}

Final result:

import Network

final class NetworkMonitor {
    
    var isNetworkAvailable: Bool {
        monitor.currentPath.status == .satisfied
    }
    
    private let monitor = NWPathMonitor()
    private let queue = DispatchQueue(label: "network-monitor")
    
    func startMonitoring(_ completion: @escaping (Bool) -> Void) {
        monitor.pathUpdateHandler = { path in
            DispatchQueue.main.async {
                completion(path.status == .satisfied)
            }
        }
        
        monitor.start(queue: queue)
    }
    
    func stopMonitoring() {
        monitor.cancel()
    }
    
}

Simulator

This framework may not function correctly on the simulator. This issue has existed for several years and has not yet been resolved at the time of writing this article. However, it works as expected on a real device.

Conclusion

Apple introduced this convenient tool in iOS 12. Unfortunately, this framework’s behavior may not be ideal on the simulator. Nevertheless, this tool allows you to set up internet connection status monitoring in just a few lines of code.