Introduction
NWPathMonitor is a class in Network framework, which observes network status and monitor network interface. It’s available in iOS 12 or later.
import Network
You must retain NWPathMonitor instances to get callbacks.
class NetworkMonitorViewController: ViewController {
let monitor = NWPathMonitor()
}
requiredInterface
lets you observe the specific network interface.
let wifiMonitor = NWPathMonitor(requiredInterfaceType: .wifi)
Here is the list of interfaces that NWPathMonitor supports.
https://developer.apple.com/documentation/network/nwinterface/interfacetype
Detect network changes
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
// Connected
}
}
Start observation
Create a background queue, then pass it to start()
.
let queue = DispatchQueue.global(qos: .background)
monitor.start(queue: queue)
That’s it. Simple right?
What is NWPath btw?
NWPath contains information such as available interfaces, iPv6 or iPv4.
You can retrieve it from currentPath
.
monitor.currentPath
Wrap up
I introduced NWPathMonitor to explain how it enable you to write such a plain code to detect network changes.
NWPathMonitor is
- Available in iOS 12.
- Simple to use
- Good enough for Reachability Replacement