0

I have a TableView that recieves data from a server and all works fine.

- (void)viewDidLoad
{
    [super viewDidLoad];

    // retrieveData is a method that Loads the Content
    [self retrieveData];

}

But If the user has no internet, the app crashs. How Can I check this connectivity for, if is Ok I load the data.. and If IS NOT OK, i send a NSAlert to the user?

  • **Reachability class** [Here is example of code from Apple that explain how to monitor the network state.](https://developer.apple.com/Library/ios/samplecode/Reachability/Introduction/Intro.html) – Tom Popis Apr 14 '14 at 17:43

3 Answers3

1

You can check for internet connection as given below and hope you can implement UIAlertview on yours.

// Checks if we have an internet connection or not
- (void)testInternetConnection
{   
    internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];

    // Internet is reachable
    internetReachableFoo.reachableBlock = ^(Reachability*reach)
    {
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Yayyy, we have the interwebs!");
        });
    };

    // Internet is not reachable
    internetReachableFoo.unreachableBlock = ^(Reachability*reach)
    {
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Someone broke the internet :(");
        });
    };

    [internetReachableFoo startNotifier];
}

This is well explained by iWasRobbed here.

Courtesy:- https://stackoverflow.com/a/3597085/1865424

Community
  • 1
  • 1
Kundan
  • 3,084
  • 2
  • 28
  • 65
0
  1. Do a google search for the "Reachability" class from Apple.
  2. Make your code bullet proof enough so that it won't crash even if there is no internet.
Owen Hartnett
  • 5,925
  • 2
  • 19
  • 35
  • You can also check out AFNetworking. They have an expanded version of Reachability. – Pete42 Apr 14 '14 at 17:43
  • It sounds like a little more than just Reachability. If you're not connected, you should time out and get an error, not have your app crash, so he's got some dependent code that relies on having data from the internet which is causing him to crash. That's probably more important than his reachability, because internet connection can rapidly turn on and off (think of a rider on a train with no wi-fi). – Owen Hartnett Apr 14 '14 at 17:46
0

Once you have downloaded and imported Reachbility.m and Reachbility.h files

create a helper function:

-(BOOL)IsConnected{
  Reachability *reachability = [Reachability reachabilityForInternetConnection];
  NetworkStatus networkStatus = [reachability currentReachabilityStatus];

  return !(networkStatus == NotReachable);    
}

Then use it

if([self IsConnected]){
 [self retrieveData];
}
else{
  //not connected to internet!
}
meda
  • 45,103
  • 14
  • 92
  • 122