I'm new to iOS development and am struggling to get the reachability.h class to work. Here is my code for view controller:
- (void)viewWillAppear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(checkNetworkStatus:)
name:kReachabilityChangedNotification
object:nil];
internetReachable = [Reachability reachabilityForInternetConnection];
[internetReachable startNotifier];
}
- (void)checkNetworkStatus:(NSNotification *)notice {
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
NSLog(@"Network status: %i", internetStatus);
}
It looks ok but nothing is appearing in the xcode console when running the app and switching to that view.
I'm using Reachability 2.2 and iOS 4.2.
Is there something obvious that I am doing wrong?
You can use the function usesInterfaceType(_:) to check which interface type this network path uses. This is the most effective way to figure out if your app is connected over WiFi, cellular or ethernet. print(“It's WiFi!”)
Make sure that your device is connected to a Wi-Fi or cellular network. Tap Settings > General > About. If an update is available, you'll see an option to update your carrier settings. To see the version of carrier settings on your device, tap Settings > General > About and look next to Carrier.
Network Reachability is the network state of the user's device. We can use it to understand if the device is offline or online using either wifi or mobile data. There are many ways to Check Network Reachability in Swift and many framework exist.
EDITED: If you want to check reachability before some code execution you should just use
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if (internetStatus != NotReachable) {
//my web-dependent code
}
else {
//there-is-no-connection warning
}
You can also add a reachability observer somewhere (i.e. in viewDidLoad
):
Reachability *reachabilityInfo;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myReachabilityDidChangedMethod)
name:kReachabilityChangedNotification
object:reachabilityInfo];
Don't forget to call [[NSNotificationCenter defaultCenter] removeObserver:self];
when you no longer need reachability detection (i.e. in dealloc
method).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With