Any good mobile application would keep a track or at least check whether the network is reachable or not as the iPhone may have a bad reception or the WIFI may not be connected etc. This is also a requirement by Apple for application submission that the application must implement and check for Reachability so that the apps don’t crash or hang while performing a network related operation. This helps ensure a good application experience.

Code

– (BOOL) connectedToNetwork
{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;

    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);

    if (!didRetrieveFlags)
    {
        NSLog(@"Error. Could not recover network reachability flags");
        return NO;
    }

    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
        BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;

        NSURL *testURL = [NSURL URLWithString:@"http://www.apple.com/"];
        NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
        NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self];

    return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;
}