views:

1455

answers:

3

I am using NSURLConnection in an iPhone app as so:

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest: request delegate: self];

The request has been setup and works properly, but I want to be able to provide a "connection not available" message to the user if there isn't a connection available. Is there a quick way to determine whether an Internet connection is available on the iPhone?

Would something as simple as adding the following after initing the NSURLConnection:

if (conn) { // do normal processing } else { // display connection not available message }

Thanks in advance, Ben

+4  A: 

this works for me and is taken from apple seismic xml project:

- (BOOL)isDataSourceAvailable
{
    static BOOL checkNetwork = YES;
    if (checkNetwork) { // Since checking the reachability of a host can be expensive, cache the result and perform the reachability check once.
        checkNetwork = NO;

        Boolean success;    
        const char *host_name = "twitter.com"; // your data source host name

        SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host_name);
        SCNetworkReachabilityFlags flags;
        success = SCNetworkReachabilityGetFlags(reachability, &flags);
        _isDataSourceAvailable = success && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
        CFRelease(reachability);
    }
    return _isDataSourceAvailable;
}
Raj
+1  A: 

Raj, that code works, but doesn't always create the desired result.

The way that the TCP stack on the iPhone works is very different from what should be expected. With the "Reachability" code, sometimes a network connection will be present, but will not be reliably detected. However, launching MobileSafari then reattempting to check connectivity with "Reachability" code (Raj's code) will result in the correct result.

The way that I have found most effective in determining network connectivity is to run a NSURLConnection check when the application loads, in a separate thread. Make a call to a URL that you know will return something like "Yes" (i.e. HTML file on your server or something). Then check to be sure the returned result is equal to the static text. That way, you know that the NSURLConnection stack is reaching out properly, as opposed to the "Reachability" code that does not quite work consistently.

Jason
@jasonb - the only problem with this approach is the time it takes to do this check - you dont want your users to wait for seconds just to detect internet. i used to do it the same style earlier but changed my code as i heard apple rejects apps if they take forever to detect internet
Raj
@Raj - You can send the process out to another NSThread if you don't need Internet access the second the application starts.
Jason
A: 

strong text*

tushar