Question

I would like to use Reachability to check for an Internet connection in my application.

I have found a tutorial which walks through setting this up in the application. In the tutorial it explains about 'Step 4' - a Reachability Manager. It mentions the following:

This is useful if an object needs direct access to the reachability instance that the singleton object manages.

What would be an example of this? What object would need direct access to the instance?

Within my application I have multiple methods which require an internet connection to be run. What I am trying to achieve is one of two approaches:

  1. Show a UIAlertView when the internet connection is lost asking the user to retry.

    Note: This is only on certain view controllers and not through out the application as I do not need to completely restrict access through out.

  2. OR - I would like to use a method to check an internet connection exists before running the actual method that requires the connection.

How can I set this up using Reachability in this way?

Was it helpful?

Solution

In 4th sections there's an example of wrapper for Reachability (but in that realization there's no kReachabilityChangedNotification handling). So how should you use it? — As you can see in interface of MTReachabilityManager, there're 1 method for getting singleton instance of manager and 4 methods for working with it:

+ (BOOL)isReachable;
+ (BOOL)isUnreachable;
+ (BOOL)isReachableViaWWAN;
+ (BOOL)isReachableViaWiFi;

For your second approach in method that want connection You have to do something like:

if ([[MTReachabilityManager sharedManager] isReachable]) {
     //do internet
} else {
     //alert 'no internet' or something
}

For first approach (connection was lost during getting data from network) this wrapper would not help you (not implemented listening of kReachabilityChangedNotification). So you have to add code from section 3 (Step 3: Notifications) of this tutorial — add listener for kReachabilityChangedNotification somewhere before call network code:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityDidChange:) name:kReachabilityChangedNotification object:nil];

and add method to handle notifications (will be fired when internet changed it's state):

- (void)reachabilityDidChange:(NSNotification *)notification {
    Reachability *reachability = (Reachability *)[notification object];
    if ([reachability isReachable]) {
        NSLog(@"Reachable");
        //if before there was no internet - now you can do whatever user wants when there was no internet
    } else {
        NSLog(@"Unreachable");
        //alert retry
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top