Search code examples
iosnsurlconnectionreachability

Reachability : Detect when network is reconnected


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?


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
      }
    
    }