TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

How to check for internet connectivity using NWPathMonitor

Swift version: 5.6

Paul Hudson    @twostraws   

Apple’s Network framework provides a number of useful classes for working with network data, including one specifically designed to monitor network accessibility: NWPathMonitor. If you ever used Apple’s older Reachability system, NWPathMonitor replaces it fully.

To get started, first add an import for the Network framework:

import Network

Next, create an instance of NWPathMonitor somewhere it won’t get freed immediately. For example, you might have it as a property on a view controller, for example:

let monitor = NWPathMonitor()

Now assign a closure to that monitor that will be triggered whenever network accessibility changes. This needs to accept one parameter, which is an NWPath describing the network access that is currently possible.

NWPath has a few properties, but there are two in particular you’re likely to care about: status describes whether the connection is currently available or not, and isExpensive is set to true when using cellular data or when using WiFi that is hotspot routed through an iPhone’s cellular connection.

To try this out, here’s some code that prints a message when the user’s connection status changes, and also prints whether the connection is considered expensive or not:

monitor.pathUpdateHandler = { path in
    if path.status == .satisfied {
        print("We're connected!")
    } else {
        print("No connection.")
    }

    print(path.isExpensive)
}

Remember, that closure gets called every time the connection status changes.

Once your path monitor is created and configured, the final step is to create a custom DispatchQueue instance for the monitor to run, then call its start() method:

let queue = DispatchQueue(label: "Monitor")
monitor.start(queue: queue)

Once that’s done, your closure will get called every time the connection status changes, so you can add code there to update the rest of your app with the current connection status.

If you want more fine-grained control over the network check, you can create your NWPathMonitor using a specific interface type. For example, if you specifically wanted to check for cellular data and only cellular data, you would write this:

let cellMonitor = NWPathMonitor(requiredInterfaceType: .cellular)

You can also use .wifi or even wiredEthernet if you want. Omitting the interface type causes them all to be watched at the same time, which is probably what you’ll want most of the time.

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 12.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.5/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.