Question

I am new to iOS and just started working on it. I am trying to implement network reachability to detect when the network is disconnected and when it gets back by using a third party class. I am able to detect the loss of network but I am not able to detect when the network gets back after it is disconnected. I am using the following condition for checking the disconnection which is working well :

// NSURLConnectionDelegate method: Handle the connection failing
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
   Reachability    *reachability    =   [Reachability reachabilityForInternetConnection];
   [reachability startNotifier];
   NetworkStatus   internetStatus  =   [reachability currentReachabilityStatus];

   if(internetStatus==NotReachable)
   {
     NSLog(@" Network Disconnected")
   }
}

I have downloaded the third party reachability class from this link :https://github.com/tonymillion/Reachability

Can anyone suggest me the way to detect when the network is connected again?

Was it helpful?

Solution

You can simply place a notification in your class like this:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

And then, you can use thiis method to observe when the network connection gets back i.e the connection state changes:

- (void) reachabilityChanged:(NSNotification *)note
{
 Reachability* currentReach = [note object];
 NSParameterAssert([currentReach isKindOfClass:[Reachability class]]);
  if (internetStatus != NotReachable)
  {
     // handle UI as per your requirement
  }

}

OTHER TIPS

You called

[reachability startNotifier];

it means that each time reachabilty status is changed it will emit kReachabilityChangedNotification. So what you need now is to subscribe to receive this notification:

[[NSNotificationCenter defaultCenter]
 addObserver:self 
 selector:@selector(reachabilityStatusChanged:) 
 name:kReachabilityChangedNotification 
 object:nil];

and implement reachabilityStatusChanged: method:

- (void)reachabilityStatusChanged:(NSNotification *)notice {
   Reachability    *reachability    =   [Reachability reachabilityForInternetConnection];
   NetworkStatus   internetStatus  =   [reachability currentReachabilityStatus];

   if (internetStatus != NotReachable)
   {
      // do what you need
   }

}

Download Reachability.h from this:

https://developer.apple.com/Library/ios/samplecode/Reachability/Introduction/Intro.html

and subscribe to notification:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top