Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use reachability class to detect valid internet connection?

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?

like image 247
Camsoft Avatar asked Mar 04 '11 14:03

Camsoft


People also ask

How does Nwpathmonitor check Internet connection?

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!”)

How do I check my network on IOS?

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.

What is reachability in IOS Swift?

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.


1 Answers

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).

like image 105
knuku Avatar answered Oct 21 '22 14:10

knuku