I want functionality similar to AFNetworking
in Objective-C with Alamofire NetworkReachabilityManager in Swift:
//Reachability detection
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN: {
[self LoadNoInternetView:NO];
break;
}
case AFNetworkReachabilityStatusReachableViaWiFi: {
[self LoadNoInternetView:NO];
break;
}
case AFNetworkReachabilityStatusNotReachable: {
break;
}
default: {
break;
}
}
}];
I am currently using the listener to know the status changes with network
let net = NetworkReachabilityManager()
net?.startListening()
Can someone describe how to support those use cases?
I found the answer myself i.e by just writing a listener with closure as mentioned below:
Here's my implementation. I use it in a singleton. Remember to hold on to the reachability manager reference.
Using a singleton is working as I long as you keep a reference of reachabilityManager
So you can use it like this anywhere in your app:
You will be notified of any change in your network status. Just for icing on the cake this is a very good animation to show on your internet connection loss.
NetworkManager Class
Start Network Reachability Observer
Apple says to use a struct instead of a class when you can. So here's my version of @rmooney and @Ammad 's answers, but using a struct instead of a class. Additionally, instead of using a method or function, I am using a computed property and I got that idea from this Medium post by @Abhimuralidharan. I'm just putting both the idea of using a struct instead of a class (so you don't have to have a singleton) and using a computed property instead of a method call together in one solution.
Here's the struct NetworkState:
Here is how you use it in any of your code: