Check internet connection on iPhone

People (especially iPhone developers) watch out! If your iPhone app relies on any kind of internet back-end-service, don’t forget to check if the service is available and even more to check if a internet connection is currently possible (for instance there is no network or the iPhone is in flight mode).

If you don’t provide enough information to your users, that your iPhone app needs a valid internet connection or your back-end-service is currently not available, Apple may reject your iPhone App.

You will find several examples how to achieve that at the web. The following code I found several times at stackoverflow.com could be very useful for you:

 
- (void) someMethod {
    const char *host_name = "blackwhale.at";
    if( [self checkConnection:host_name] ) {
        //everything is ok
    }
    else {
        //notify your users
    }
}
 
/**
 * checkConnection:
 * Check if the given host is reachable with the 
 * current network settings
 */
- (BOOL) checkConnection:(const char*) host_name {
    BOOL _isDataSourceAvailable = NO;
    Boolean success;    
 
    //Creates a reachability reference to the specified 
    //network host or node name.
    SCNetworkReachabilityRef reachability = 
            SCNetworkReachabilityCreateWithName(NULL, host_name);
 
    //Determines if the specified network target is reachable 
    //using the current network configuration.
    SCNetworkReachabilityFlags flags;
    success = SCNetworkReachabilityGetFlags(reachability, &flags);
    _isDataSourceAvailable = success && 
                (flags & kSCNetworkFlagsReachable) &&
                !(flags & kSCNetworkFlagsConnectionRequired);
 
    CFRelease(reachability);
 
    return _isDataSourceAvailable;
}

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

1 Response to “Check internet connection on iPhone”


Leave a Reply