I have some swift code which uses the Network framework to detect when network connectivity is available or not. If I have wifi turned on and I run my code my code reports that path.status is .satisfied and if I then turn off my wifi my code reports that path.status is .satisfied again. But then if I turn on my wifi again path.status is reported as .unsatisfied then a second later it reports it as .satisfied. What on earth is going on? I would expect path.status to change immediately when wifi is turned off and on and off etc.
Here is my NetworkServices class;
final class NetworkServices {
static let sharedInstance = NetworkServices()
private let queue = DispatchQueue.global(qos: .background)
private let monitor: NWPathMonitor
public private(set) var isConnected: Bool = false
public private(set) var connectionType: ConnectionType = .unknown
enum ConnectionType {
case wifi
case cellular
case wiredEthernet
case unknown
}
private init() {
monitor = NWPathMonitor()
}
public func startMonitoring() {
monitor.start(queue: queue)
monitor.pathUpdateHandler = { [weak self] path in
self?.isConnected = path.status == .satisfied
print("DEBUG: path.status = \(path.status); isConnected = \(self!.isConnected)")
self?.getConnectionType(path)
}
}
public func stopMonitoring() {
monitor.cancel()
}
private func getConnectionType(_ path: NWPath) {
if path.usesInterfaceType(.wifi) {
connectionType = .wifi
} else if path.usesInterfaceType(.cellular) {
connectionType = .cellular
} else if path.usesInterfaceType(.wiredEthernet) {
connectionType = .wiredEthernet
} else {
connectionType = .unknown
}
}
}
I call the startMonitoring method in my AppDelegate file's didFinishLaunchingWithOptions method
As you turn on wifi, It notify for
NWPathupdate but until then connection has not been established, it takes some moment to connect.