简体   繁体   中英

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

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.

-(BOOL)NetworkConnectionCheck {
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    return [reachability isReachable];                                                                                                                                               
}

-(void)viewDidLoad {
if (!self.NetworkConnectionCheck) { // checks active network connection
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"There are no active wifi or data connection!" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
            [alert show];           
 } else {
       // do your refresh stuff here......
}

Quick way to check network connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM