Swift version: 5.6
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.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Available from iOS 12.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.