Jon Jon - 3 months ago 14
Objective-C Question

How to detect change in network with Reachability?

I'm currently checking network connection on

viewDidLoad
using this:

-(BOOL)reachable {
ReachabilityDRC *r = [ReachabilityDRC reachabilityWithHostName:@"google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if(internetStatus == NotReachable) {
return NO;
}
return YES;
}


But I also want to be notified if there is a change of network, such as wifi dropped, or wifi is back, so I can make changes accordingly.

How can I adjust my method to do something like that?

Answer

Another possible solution is to add a NS Notification in "application didfinishlaunching":

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

and in checkForReachability method do this:

    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    [reachability startNotifier];

    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

    if(remoteHostStatus == NotReachable) {
        //Do something
    }
     else if (remoteHostStatus == ReachableViaWiFi) {
    // Do something
 }
    else{

// Else do something else
}