user836026
user836026

Reputation: 11350

How to detect if there no internet connection

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

Upvotes: 0

Views: 4062

Answers (2)

Sowjanya lankisetty
Sowjanya lankisetty

Reputation: 210

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];

Upvotes: 1

Pankaj Khairnar
Pankaj Khairnar

Reputation: 3108

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

Upvotes: 0

Related Questions