Reputation: 955
I am using the Almofire for the network reachability. Here is the scenario:
class ReachabilityManager: NSObject {
static let shared = ReachabilityManager()
let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "my.server.url")
var isReachable : Bool {
return reachabilityManager?.isReachable ?? false
}
}
Upvotes: 0
Views: 751
Reputation: 1
let reachability = Reachability()!
//This function is find to wifi or Cellular network
reachability.whenReachable = { reachability in
if reachability.connection == .wifi {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
//When Network is Off This Function Call
reachability.whenUnreachable = { _ in
print("Not reachable")
}
//This code is automatically call when network is on.
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
Upvotes: 0
Reputation: 2872
Maybe try replacing reachability with NWPathMonitor
.
It has been more reliable and gives you more options.
Here's an example:
import Network
let monitor = NWPathMonitor()
func monitorNetwork() {
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
connectionAvailable = true
} else {
connectionAvailable = false
}
}
let queue = DispatchQueue(label: "Net")
monitor.start(queue: queue)
}
You can also check if user is using cellular data or is connected to a hotspot:
path.isExpensive
As per documentation:
A Boolean indicating whether the path uses an interface that is considered expensive, such as Cellular or a Personal Hotspot.
Furthermore you can check various connection requirments or types:
let monitor = NWPathMonitor(requiredInterfaceType: .cellular)
This gives you more options like: .wifi, wierdEthernet, loopback, other.
See documentation on: NWInterface.InterfaceType
Upvotes: 0