john doe
john doe

Reputation: 9660

Checking the Internet Connection iOS App

In my splash screen I subscribe to the UIApplicationDidBecomeActiveNotification.

 - (void)viewDidLoad
{
    [super viewDidLoad];


    // register notifications

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkInternetConnection:) name:UIApplicationDidBecomeActiveNotification object:nil];

}

-(void) checkInternetConnection:(NSNotification *) notification
{
    internetStatus = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus];

    if(internetStatus == NotReachable)
    {
        [AppHelper showAlert:@"ERROR" message:@"Error downloading data. Please check your network connection and try again." cancelButtonTitle:nil otherButtonTitles:@[@"OK"]];
        return;
    }

    [self viewDidAppear:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if(!(internetStatus == NotReachable))
    {
        AppDelegate *applicationDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        [applicationDelegate performSelector:@selector(showMainMenu) withObject:[NSNumber numberWithBool:YES] afterDelay:3.0];
    }
}

The problem is that the internet connection will only be checked on the splash screen so if I am in the middle of some other screen and I loose internet connectivity then there is no way to tell that the connection has been gone. How can I make a good logic to check for the client's internet connection.

Upvotes: 1

Views: 1413

Answers (2)

savner
savner

Reputation: 840

I would recommend creating a class that all internet requests filter though and check for connectivity (using Reachability as suggested) within that class. If you architect it that way it should simplify things a bit.

Upvotes: 0

Wain
Wain

Reputation: 119021

You want to use a reachability library which allows you to get callbacks about changes (like this one).

Then, in each controller that requires it, create a reachability instance and set the reachableBlock and unreachableBlock to perform your required actions.

Upvotes: 1

Related Questions