Search code examples
iosobjective-creachability

How do I use Reachability to check if there's an internet connection, and if not, do something. (Basically use as a boolean.)


I've read over the code on Reachability's page, but I'm unclear as to how I'd use it in an if statement type scenario.

For example, the user taps the refresh button, firing the refresh method (go figure, eh?) and if there is an internet connection, I want the refresh of data to occur, but if not, I want to send a notification of no internet.

How would I achieve something like this with Reachability?

Would I just use code like the following but have a variable set to a value in each block depending on the result, and just look at it after. That seems less than elegant, but if it's the only way, so be it.

// allocate a reachability object
Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];

// set the blocks 
reach.reachableBlock = ^(Reachability*reach)
{
    NSLog(@"REACHABLE!");
};

reach.unreachableBlock = ^(Reachability*reach)
{
    NSLog(@"UNREACHABLE!");
};

// start the notifier which will cause the reachability object to retain itself!
[reach startNotifier];

Solution

  • My app did just that - send a message in the block to self on the main thread - say hostChanged:(BOOL)state. Your self class can then maintain a public ivar of the state, or and a notification other objects can listen for.

    My app had this function in the app delegate so it was easy for other objects to get to it.

    Note that it takes iOS tens of seconds to determine the state, so my code launched with he assumption of UP.