0

How could I detect when there no internet connection. or if connection time out. I'm using NSURLConnection class.

user836026
  • 10,608
  • 15
  • 73
  • 129
  • 1
    You can use the `Reachability` class as explained in: [How to use reachability class to detect valid internet connection?](http://stackoverflow.com/questions/5195012/how-to-use-reachability-class-to-detect-valid-internet-connection) – sch Mar 22 '12 at 20:46
  • 1
    duplicate of: http://stackoverflow.com/questions/1083701/how-to-check-for-an-active-internet-connection-on-iphone-sdk – Sebastian Flückiger Mar 22 '12 at 20:57

2 Answers2

1

Apple provides you Reachability class, add this to ypur project. Import Reachability.h and Reachability.m files. Add systemConfiguration frame work. And add the following snippet in your code.

Reachability *internetReachableinst;
internetReachableinst= [Reachability reachabilityWithHostName:@"www.google.com"];
internetReachableinst.reachableBlock = ^(Reachability*reach)
    {

        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Internet is connected");
        });
    };

   //Internet is not reachable
    internetReachableinst.unreachableBlock = ^(Reachability*reach)
    {

        //Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"No internet");
        });
   };
   [internetReachableinst startNotifier];
0

The easiest way to check internet connectivity is using following code.

NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
NSString *result = [[NSString alloc] init];
result = ( URLString != NULL ) ? @"Yes" : @"No";
NSLog(@"Internet connection availability : %@", result);

but this code has to rely on the availability of google.com

Pankaj Khairnar
  • 3,028
  • 3
  • 25
  • 34