Take the 2-minute tour ×

I am trying to detect if there is an error in my request using the if statement on theConnection. It enters the first part if successful fine but does not enter the else if there is an error. I am not sure why.

- (void)vehicleSearchRequest:(NSData *)postBodyData

    NSString *address = [NSString stringWithFormat:@"http://%@", serverAddress];

    //Set database address
    NSMutableString *databaseURL = [[NSMutableString alloc] initWithFormat:@"%@", address];

    NSURL *url = [NSURL URLWithString:databaseURL];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postBodyData length]];

    //SynchronousRequest to grab the data, also setting up the cachePolicy
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //if request dose not finish happen within 60 second timeout.

    // Set up request
    [request setHTTPMethod: @"POST"];
    [request setValue:@"application/octet-stream" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody:postBodyData];
    [request setTimeoutInterval:180];

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

    if (theConnection) {
        // do animation thankyou here
        [self submitSuccessful];
    } else {
        // Inform the user that the connection failed from the connection:didFailWithError method
        NSLog(@"Connectin ERROR!!!");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection error, Please try again" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

        [alert show];

share|improve this question
You won't get a nil theConnection object for all types of failures. Some errors are apparent immediately, and others only show up after a while (for example, a timeout), in which case, you'll find out in the didFailWithError: callback. –  Nate Feb 21 '13 at 2:49
cool I fixed it with your suggestion... oppsie. –  HurkNburkS Feb 21 '13 at 2:54
What do you get when you NSLog(@"conn: %@", theConnection); right after the initialization? –  Ares Feb 21 '13 at 3:03
Here is a working example.. Link seems pretty explanatory to me. –  chuthan20 Feb 21 '13 at 3:32
Where is the delegate methods of NSURLConnection ?? didFail, didReceive, didFinish etc??? –  Satish Azad Feb 21 '13 at 6:24
show 5 more comments

1 Answer

Your code checks to see whether it was able to instantiate an NSURLConnection or not. This is a useful safety check, but will only fail in practice if you pass it a URL that the system does not support.

The connection itself is asynchronous, and so will take a little while to tell you if there was a problem or not. Implement its delegate methods to hear back from the server.

share|improve this answer
add comment

Your Answer


