Search code examples
iphonexcodeuiwebviewalertreachability

iPhone app, alert users when they aren't connected to the internet?


What's an easy way to code an alert that warns users when they aren't connected to the Internet? I'm using Xcode, right now when there is no connection it is just a white screen in uiwebview.


Solution

  • Here you can check if wifi has connection, 3g,or none atall:

    if ([[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == ReachableViaWiFi) {
        // Do something that requires wifi
    } else if ([[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == ReachableViaWWAN) {
        // Do something that doesnt require wifi
    } else if ([[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == NotReachable) {
        // Show alert because no wifi or 3g is available..
    }
    

    Apple provides all the necessary Reachability api/source here: Reachability Reference


    I have made these custom convenience functions for myself in all my projects:

    + (BOOL)getConnectivity {
        return [[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] != NotReachable;
    }
    
    + (BOOL)getConnectivityViaWiFiNetwork {
        return [[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == ReachableViaWiFi;
    }
    
    + (BOOL)getConnectivityViaCarrierDataNetwork {
        return [[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == ReachableViaWWAN;
    }
    

    And used like so:

    if ([ServerSupport getConnectivity]) {
        // do something that requires internet...
    else {
        // display an alert
        UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Network Unavailable" 
                                                         message:@"App content may be limited without a network connection!" 
                                                        delegate:self 
                                               cancelButtonTitle:@"OK" 
                                               otherButtonTitles:nil] autorelease];
        [alert show];
    }