Have you considered monitoring your network connectivity using NWPathMonitor?
For example, to monitor WiFi and Cellular:
var monitorWiFi = NWPathMonitor(requiredInterfaceType: .wifi)
var monitorCellular = NWPathMonitor(requiredInterfaceType: .cellular)
var isInternetAvailableOnWiFi: Bool = false
var isInternetAvailableOnCellular: Bool = false
Then...
/// **startPathMonitors**
/// Monitor the WiFi and Cellular connections
/// Note: NWPathMonitor checks for connection to wider network
///
func startPathMonitors() {
/// WiFi
monitorWiFi.pathUpdateHandler = { path in
/// This closure is called every time the connection status changes
DispatchQueue.main.async {
switch path.status {
case .satisfied:
print("PathMonitor WiFi satisfied, interface: \(path.availableInterfaces) gateways: \(path.gateways)")
default:
print("PathMonitor WiFi not satisfied: \(path.unsatisfiedReason)")
}
self.isInternetAvailableOnWiFi = (path.status == .satisfied)
}
}
monitorWiFi.start(queue: DispatchQueue(label: "monitorWiFi"))
/// Cellular
monitorCellular.pathUpdateHandler = { path in
/// This closure is called every time the connection status changes
DispatchQueue.main.async {
print("PathMonitor Cellular: \(path.status)")
self.isInternetAvailableOnCellular = (path.status == .satisfied)
}
}
monitorCellular.start(queue: DispatchQueue(label: "monitorCellular"))
}