3

I have implemented Reachability Api 2.2. When the network goes from an off state to an on state it does not fire.

In addition, can I implement it in the app delegate? If so, where should I remove observer?

Here is my code (which does not call dismiss model viewController)

- (void)viewDidLoad
{
    // check for internet connection
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

     internetReachable = [[Reachability reachabilityForInternetConnection] retain] ;
    [internetReachable startNotifier];
    // check if a pathway to a random host exists
    hostReachable = [[Reachability reachabilityWithHostName: @"www.google.com"] retain];
    [hostReachable startNotifier];
 }

- (void) checkNetworkStatus:(NSNotification *)notice
{
    // called after network status changes

    NetworkStatus hoststatus=[hostReachable currentReachabilityStatus];

    NetworkStatus internetStatus=[internetReachable currentReachabilityStatus];

    for (NSString *msg  in messageArray) {
        [stringg appendString:[NSString stringWithFormat:@"%@",msg]]; 
    }

    if  (hoststatus==NotReachable||internetStatus==NotReachable) {
        [self.navigationController presentModalViewController:inter animated:YES];
    }
    else{
        [self dismissModalViewControllerAnimated:YES];
    }

    [inter release];
} 



- (void)viewDidUnload
{

    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super viewDidUnload];
}
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Mann
  • 5,477
  • 6
  • 45
  • 57

2 Answers2

1

Where are you registering for notifications?

You need something like this:

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

I use the reachability object passed as a parameter like this:

- (void) reachabilityChange: (NSNotification*) notification
{
    Reachability* curReach = [notification object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    BOOL isServerCurrentlyReachable = (NotReachable != [curReach currentReachabilityStatus]);
    BOOL wasServerPreviouslyReachable = self.isServerReachable;
    self.isServerReachable = isServerCurrentlyReachable;

    if (NO == wasServerPreviouslyReachable && YES == isServerCurrentlyReachable)
    {
        // Moving from non reachable to reachable state

    }
    else if (YES == wasServerPreviouslyReachable && NO == isServerCurrentlyReachable)
    {
        // Moving from a reachable to a non reachable state

    }
}

You don't seem to be using that.

Also the notification can get called several times with the same status, so you need to make sure this is accounted for, as done in the snippet.

If you're using it in the app delegate, stopping/removing stuff in the applicationDidResignActive would seem to be the appropriate place.

Gruntcakes
  • 37,738
  • 44
  • 184
  • 378
  • Yah i have added that but still. Actually if i restart my modem then it detects network down. but when network goes on then it does not detect that. While if i turn off wifi from mac then it detects on and off both – Mann May 28 '12 at 22:58
  • You're not using the reachability instance passed as a parameter – Gruntcakes Jun 03 '12 at 00:27
0

Include Reachability.h and Reachability.m files from developer apple to your project.Import SystemConfiguration framework from SDK libraries to your project.Then add the following GlobalFunction.h and GlobalFunction.m files to your project

//GlobalFunction.h


#import <Foundation/Foundation.h>

@class Reachability;

@interface GlobalFunction  :  NSObject
{
Boolean internetActive;
Boolean hostActive;

Reachability * internetReachable;
Reachability * hostReachable;
Reachability * wifiReach;

}

@property (readwrite,assign) Boolean internetActive;
@property (readwrite,assign) Boolean hostActive;

 - (Boolean) checkNetworkStatus;
 - (BOOL)connectedToNetwork;
 @end


 //GlobalFunction.m

 #import "GlobalFunction.h"
 #import "Reachability.h"
 #include <netinet/in.h>
 #import <SystemConfiguration/SCNetworkReachability.h>

 @implementation GlobalFunction

  @synthesize  internetActive,hostActive;
  - (id)init
   {
 self = [super init];
  if (self) {
 // Initialization code here.
     }

 return self;
 }



 //  Checking Internet Connectivity
 - (Boolean) checkNetworkStatus//:(NSNotification *)notice
  {
 // called after network status changes
  internetReachable = [[Reachability reachabilityForInternetConnection] retain];
    [internetReachable startNotifier];

   // check if a pathway to a random host exists
  hostReachable = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain];
     [hostReachable startNotifier];

   NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
  switch (internetStatus)
 {
case NotReachable:
{
    //NSLog(@"The internet is down.");
    //[self ShowMsg:@"The internet connection appears to be offline."];
    self.internetActive = NO;
    break;

}
case ReachableViaWiFi:
{
    //NSLog(@"The internet is working via WIFI.");
    self.internetActive = YES;

    break;

}
case ReachableViaWWAN:
{
    //NSLog(@"The internet is working via WWAN.");
    self.internetActive = YES;

    break;

}
default :
    self.internetActive = YES;
    break;

 }

 NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
 switch (hostStatus)

  {
 case NotReachable:
 {
    //NSLog(@"A gateway to the host server is down.");
    self.hostActive = NO;

    break;

}
case ReachableViaWiFi:
{
    //NSLog(@"A gateway to the host server is working via WIFI.");
    self.hostActive = YES;

    break;

}
case ReachableViaWWAN:
{
    //NSLog(@"A gateway to the host server is working via WWAN.");
    self.hostActive = YES;

    break;

  }
 }

  [hostReachable release];
  [internetReachable release];

 return self.internetActive;
  }



  - (BOOL)connectedToNetwork
 {
  // Create zero addy
  struct sockaddr_in zeroAddress;
 bzero(&zeroAddress, sizeof(zeroAddress));
 zeroAddress.sin_len = sizeof(zeroAddress);
 zeroAddress.sin_family = AF_INET;
// Recover reachability flags 
    SCNetworkReachabilityRef defaultRouteReachability =                                                                           SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr*)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
    if (!didRetrieveFlags)
    {
//NSLog(@"Error. Could not recover network reachability flags");
return 0;
    }
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    //below suggested by Ariel
    BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
    NSURL *testURL = [NSURL URLWithString:@"http://www.apple.com/"];
   //comment by friendlydeveloper: maybe use www.google.com
  NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
  //NSURLConnection *testConnection = [[NSURLConnection alloc]     initWithRequest:testRequest delegate:nil]; //suggested by Ariel
   NSURLConnection *testConnection = [[[NSURLConnection alloc] initWithRequest:testRequest delegate:nil] autorelease];
 //modified by friendlydeveloper
   return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;

  }

-(void)dealloc 
{
internetReachable=nil;
hostReachable=nil;
 wifiReach=nil;

[super dealloc];
}

@end




  ------>Just write the code for checking internet connection
 #import<GlobalFunction.m>

-(void)viewDidLoad
   {
   if([globalFunc checkNetworkStatus])
 {
[self ShowAlert:@"Internet Connection appears"];
  }
 else
 {
[self ShowAlert:@"The Internet connection appears to be offline.."];
 }
 }
SURESH SANKE
  • 1,653
  • 17
  • 34