So I am trying to solve some issues related to the internet connection (trying to fetch data from the backend, but failing). The issue is that we do check if the device is connected to the cellular or wifi, and if it is Wifi, then we say that it is true, and the network is available.
But that is not true. It can be that the device is connected to Wifi, but Wifi is not connected to the internet for any reason.
How do I know if the device really has an internet connection? Can something similar happen on the cellular connection that it is connected, to but has no access?
Update:
Currently using Reachability
import Reachability
class NetworkReachability {
let reachability = try! Reachability()
var connectionStatus = CurrentValueSubject<Reachability.Connection, Never>(.wifi)
var isNetworkAvailable: Bool { connectionStatus.value.isAvailable }
}
extension Reachability.Connection {
var isAvailable: Bool {
switch self {
case .none, .unavailable:
return false
case .wifi, .cellular:
return true
}
}
}
The issue is that this can not detect if the device actually has the internet access or no.
There is a way to check with Firebase, but takes too long and would slow down the app a lot:
import Firebase
var isAvailable: Bool {
var isReallyAvailable = false
let connectedRef = Database.database().reference(withPath: ".info/connected")
connectedRef.observe(.value, with: { snapshot in
if let connected = snapshot.value as? Bool {
isReallyAvailable = connected
}
})
return isReallyAvailable
}
So I am looking for a better way
CodePudding user response:
You can use Network framework and check connection activity.
import Network
class NetworkMonitor: ObservableObject {
private let monitor = NWPathMonitor()
private let queue = DispatchQueue(label: "Monitor")
var isActive = false
var isExpensive = false
var isConstrained = false
var connectionType = NWInterface.InterfaceType.other
init() {
monitor.pathUpdateHandler = { path in
self.isActive = path.status == .satisfied
self.isExpensive = path.isExpensive
self.isConstrained = path.isConstrained
let connectionTypes: [NWInterface.InterfaceType] = [.cellular, .wifi, .wiredEthernet]
self.connectionType = connectionTypes.first(where: path.usesInterfaceType) ?? .other
DispatchQueue.main.async {
self.objectWillChange.send()
}
}
monitor.start(queue: queue)
}
}
CodePudding user response:
It seems like "NWPathMonitor" is the best option to check the connection status. (There is a great article by Paul Hudson on his website)