How to check for Network Connectivity in iOS

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





2 thoughts on “How to check for Network Connectivity in iOS

  1. Thanks so much.. Why isn’t Reachability built into the core? A simple “isConnected” function would do instead of all this imported ‘time consuming’ extra. A connection to the net is practically required these days.

    1. I couldn’t agree more, Luke. Tony Million wrote that the he had reports that Apple is starting to reject apps that contain the Reachability class. Iv’e not made this experience myself, but should this happen to anyone, simply rename the class. Perhaps Apple are thinking about releasing their own version of it sometime? It’s only been… 11 years and counting.

Leave a Reply

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