2

I am building an application and trying to check and see if a device is still available on the network (by connecting to the devices IPAddress). I am using reachability to confirm that it is available.

When I network access for the iOS device (turn on airplane mode for example) everything works properly, but if I remove the device from the network, reachability does not seem to notice the change.

It seems like reachability is caching the results, and not seeing the update.

Nathan
  • 1,609
  • 4
  • 25
  • 42
  • Please check your NSNotification observer. If it is getting removed while going into Background or coming to foreground. – Anil Gupta Jun 01 '17 at 08:45
  • You can check apple Reachabilty sample class: https://developer.apple.com/library/content/samplecode/Reachability/Listings/Reachability_Reachability_h.html – Anil Gupta Jun 01 '17 at 08:46

4 Answers4

2

Don't use reachability then!

Use this bit of code instead which works a treat;

NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
wait(25000);
if (connected == NULL) {

NSLog(@"Not Connected"); 
//Code to show if not connected

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Oops! You aren't connected to the Internet." 
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

} else {
NSLog(@"Connected Successfully!");
//Any other code for successful connection
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
pixelbitlabs
  • 1,934
  • 6
  • 36
  • 65
  • I was having the same issue with Nathan. Your solution is simple but work any time! the only thing I want to add is to use the new stringWithContentsOfURL format. NSError* error = nil; NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://twitter.com"] encoding:NSASCIIStringEncoding error:&error]; – user523234 Nov 01 '11 at 02:23
  • 2
    I would stay away from waiting 25 seconds to allow for the result to return. – burtlo Jan 12 '12 at 23:30
2

The SCReachability API only checks if the local hardware is configured such that it could reach the specified address; it does not actually attempt to reach it. To determine if the target is alive and kicking, you must attempt to open a connection to it.

Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
1

Check out this answer. While the pixelbit's answer is viable, burtlo is right to bring up that just waiting 25 seconds isn't a great idea. Using the NSURLConnection is much cleaner.

Community
  • 1
  • 1
scone
  • 566
  • 1
  • 4
  • 12
0

Apple updated the Reachabilty class file. You can test it with latest Xcode. here is link: Apple Reachabilty Sample Code

I tested with Xcode 8.3.1 on iPhone 6 version 10.3.1. It will notify user for change in network status.

Anil Gupta
  • 1,155
  • 1
  • 19
  • 26