How to use reachability class to detect valid internet connection?

Camsoft picture Camsoft · Mar 4, 2011 · Viewed 31.8k times · Source

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?

Answer

knuku picture knuku · Mar 4, 2011

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