Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reachability network change event not firing

My iphone app is pretty simple with one view that handles everything, in viewDidLoad I check to see if we have an internet connection and if we do we load from the web and if not we load from a local resource. And this works fine.

//in viewDidOnload    
[[NSNotificationCenter defaultCenter] addObserver:self 
                                          selector:@selector(handleNetworkChange:) 
                                          name:kReachabilityChangedNotification object:nil];
reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus status = [reachability currentReachabilityStatus];

if (status == NotReachable) {
    //Do something offline
} else {
    //Do sometihng on line
}

- (void)handleNetworkChange:(NSNotification *)notice{
 NetworkStatus status = [reachability currentReachabilityStatus];
 if (status == NotReachable) {
  //Change to offline Message
 } else {
  //Relaunch online application
 }

}

To test my handleNetworkChange event I turned off all cellular data but left the wifi on. Within range of the wifi I started the app and everything works perfect. Then I walk outside of the wifi's range, but my handleNetworkChange never fires (tested using an uiAlertView). Standing outside of the wifi's range my app launches the offline message just fine.

My suspicion is that it is an issue with the ViewController's lifecycle, should this code be placed in the AppDelegate function? Possibly that's a better design to start with.

like image 695
ashansky Avatar asked Dec 21 '10 17:12

ashansky


1 Answers

Turns out it was a memory management issue, as I was not retaining the reachability variable, so as soon as it would go out of scope the dealloc would be called and that called the stopNotifier method. Hence no updates as I would walk out of range.

So instead of:

reachability = [Reachability reachabilityForInternetConnection];

I do

reachability = [[Reachability reachabilityForInternetConnection] retain];

and everything works!

One cool thing I learned through all of this is that you can simulate a lost connection in the simulator by simply turning Airport Off. No more having to wander around outside. :)

like image 80
ashansky Avatar answered Oct 07 '22 01:10

ashansky