Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get change in network connection notification from iOS Reachability Class?

Hi I want to capture whenever user gets a network connectivity in my application for this I have added apples Reachability class and below is the snippet I am using in my appDelegate class didFinishLaunchingWithOptions method,

Reachability* reachability = [Reachability reachabilityForInternetConnection];
        [reachability startNotifier];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

and my reachabilityChanged selector method is as below

- (void)reachabilityChanged:(NSNotification*)notification
{
    Reachability* reachability = notification.object;
    if(reachability.currentReachabilityStatus == NotReachable)
        NSLog(@"Internet off");
    else
        NSLog(@"Internet on");
}

but here I am not getting any kind of notification when I switch off my Airplane mode and when I get a network connectivity in my phone.

Am I missing anything?

like image 383
Mobile Coe Avatar asked Jul 23 '13 08:07

Mobile Coe


1 Answers

I use a variable in appdelegate to store the current network status as a bool

@property (nonatomic, assign) BOOL hasInet;

.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self setUpRechability];
}


-(void)setUpRechability
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChange:) name:kReachabilityChangedNotification object:nil];

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

    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

    if          (remoteHostStatus == NotReachable)      {NSLog(@"no");      self.hasInet-=NO;   }
    else if     (remoteHostStatus == ReachableViaWiFi)  {NSLog(@"wifi");    self.hasInet-=YES;  }
    else if     (remoteHostStatus == ReachableViaWWAN)  {NSLog(@"cell");    self.hasInet-=YES;  }

}

- (void) handleNetworkChange:(NSNotification *)notice
{
    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

    if          (remoteHostStatus == NotReachable)      {NSLog(@"no");      self.hasInet-=NO;   }
    else if     (remoteHostStatus == ReachableViaWiFi)  {NSLog(@"wifi");    self.hasInet-=YES;  }
    else if     (remoteHostStatus == ReachableViaWWAN)  {NSLog(@"cell");    self.hasInet-=YES;  }

//    if (self.hasInet) {
//        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Net avail" message:@"" delegate:self cancelButtonTitle:OK_EN otherButtonTitles:nil, nil];
//        [alert show];
//    }
}
like image 199
Lithu T.V Avatar answered Sep 20 '22 07:09

Lithu T.V