views:

187

answers:

1

How can you test a failure of NSURLConnection?

Also, how do you tell if it failed due to airplane mode or WiFi being turned off? In my tests, while the alert pops up telling the user they need to turn on WiFi, if they ignore it my App just sits there and spins waiting for a response.

+2  A: 

If your connection's delegate is self, you can something like this:

self.myConnection = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
   if ([error code] == kCFURLErrorNotConnectedToInternet)
    {
        // if we can identify the error, we can present a more precise message to the user.
        NSDictionary *userInfoDict = [NSDictionary dictionaryWithObject:@"No Connection Error"
                                                             forKey:NSLocalizedDescriptionKey];
        NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain
                                                         code:kCFURLErrorNotConnectedToInternet
                                                     userInfo:userInfoDict];
        [self handleError:noConnectionError];
    }
    else
    {
        // otherwise handle the error generically
        [self handleError:error];
    }
}
Cirrostratus