How To Check For Internet Connection In Swift

Checking internet connection is an important for apps that rely on a steady connection.

This is especially true for real time applications such as delivery services or live events. Notifying the user that the internet has stopped working and that information may be out of date is key to creating a good user experience.

Luckily, it’s quite easy to check for an internet connection with Apple’s NWPathMonitor.

How To Check For Internet Connection in Swift

First we’ll need to add an import for the Network framework at the top of our file.

import Network

Then we’ll create an instance of NWPathMonitor as a property of our view controller.

let monitor = NWPathMonitor()

Now we’ll define a closure to be called every time the internet connection changes. We’ll check the status to determine what behavior we should do in each case.

monitor.pathUpdateHandler = { pathUpdateHandler in
    if pathUpdateHandler.status == .satisfied {
        print("Internet connection is on.")
    } else {
        print("There's no internet connection.")
    }
}

Now we just need to define a DispatchQueue for this monitor to run on and start the monitor.

I’ll define the dispatch queue as a property of the view controller.

let queue = DispatchQueue(label: "InternetConnectionMonitor")

And call the start code after our closure:

monitor.start(queue: queue)

That’s it! You’ll see in console something like this when you turn on and off the internet:

Internet connection is on.
There's no internet connection.

Check if cellular data or WiFi is on in Swift

If you only want to check if cellular data is on or if Wifi is on, you can follow the same instructions above with one modification.

Define the NWPathMonitor based on the data type:

For cellular:

let monitor = NWPathMonitor(requiredInterfaceType: .cellular)

For WiFi:

let monitor = NWPathMonitor(requiredInterfaceType: .wifi)

Full Swift Code

Here’s the full code I used for this article:

import Network

class ViewController: UIViewController {

    let monitor = NWPathMonitor()
    let queue = DispatchQueue(label: "InternetConnectionMonitor")

    override func viewDidLoad() {
        monitor.pathUpdateHandler = { pathUpdateHandler in
            if pathUpdateHandler.status == .satisfied {
                print("Internet connection is on.")
            } else {
                print("There's no internet connection.")
            }
        }

        monitor.start(queue: queue)
    }

}
If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts