How to check for Network Connectivity in iOS

- by

What you really want is a method such as (BOOL)networkIsAvailable, returning YES or NO. Apple made it several megabytes long and requires you to study several years before you get to YES or NO.

I hate that! This is such a basic function on an always-connected device that I find it appalling not to have this available to all developers without hassle at all times.

Apple do give us some example code called Reachability in their documentation, which – like so many things – is hopelessly outdated and doesn’t work with ARC anymore: http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html

Thank god for the wonderful Tony Million who has updated the project and made it available on GitHub: https://github.com/tonymillion/Reachability – works with ARC and everything. It’s a simple drop-in class, exactly what we all want and need.

I salute you, Tony! Thank you very much ;-)

Here’s how to add it to your project step by step:

  1. add both Reachability.h and Reachability.m to your project
  2. add the SystemConfiguration.framework to your project
  3. in the class that needs to check for network connectivity, #import Reachability.h
  4. create a method such as this to check which network connection you’ve got:
- (void)checkForNetwork
{
    // check if we've got network connectivity
    Reachability *myNetwork = [Reachability reachabilityWithHostname:@"google.com"];
    NetworkStatus myStatus = [myNetwork currentReachabilityStatus];
    
    switch (myStatus) {
        case NotReachable:
            NSLog(@"There's no internet connection at all. Display error message now.");
            break;
            
            case ReachableViaWWAN:
            NSLog(@"We have a 3G connection");
            break;
            
            case ReachableViaWiFi:
            NSLog(@"We have WiFi.");
            break;
    
        default:
            break;
    }
}

Obviously check which host you’d like to reach. There are several other methods in this class, such as reachabilityForInternetConnection. Check out Tony’s examples on GitHub for more:

https://github.com/tonymillion/Reachability



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.