Search code examples
iphonenetwork-connection

Checking Network Availability


I use reacheability class for checking my network connectivity in my app...

Reachability *reach = [Reachability reachabilityForInternetConnection]; 
    NetworkStatus netStatus = [reach currentReachabilityStatus];    
    if (netStatus==NotReachable)
    {
        NSLog(@"NR");
    }

I need to find when the network status change (i.e when the network status changes from reachable to notreachable and vice versa).

Is there any delegates to find this thinks, Any suggestions ?


Solution

  • Used this flag kReachabilityChangedNotification to find the change in network status and passed that to a NSNotificationCenter

    Here is the code:

    NSString *host = @"https://www.apple.com"; // Put your host here
    
            // Set up host reach property
           hostReach = [Reachability reachabilityWithHostname:host];
    
                              // Enable the status notifications
                              [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
                               [hostReach startNotifier];
    
       - (void) reachabilityChanged: (NSNotification* )note
    {
        Reachability *reachability = [note object];
        NSParameterAssert([reachability isKindOfClass:[Reachability class]]);
        if (reachability == hostReach) {
            Reachability *reach = [Reachability reachabilityForInternetConnection]; 
            NetworkStatus netStatus = [reach currentReachabilityStatus];    
            if (netStatus==NotReachable)
            {
                NSLog(@"notreacheable");
            }
            else {
                NSLog(@"reacheable");
                [[NSNotificationCenter defaultCenter]postNotificationName:@"startUpdatingTable" object:nil];
            }
        }
    }