Question

I have search around and can't quite find the right answer to this, but I have this code which posts data to my web server, and I am trying to get the HTTP response, but the response keeps returning (null). I can confirm that the connection is successful because the if statement (see below) executes the appropriate code.

Here is my code:

-(void)submitAction{
    NSString *post = [NSString stringWithFormat:@"&var1=%@&var2=%@&var3=%@&var4=%@",
                      _var1, _var2, _var3, _var4];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://my-web-server.com/path-to-web-service/"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
    [request setHTTPBody:postData];

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

    NSURLResponse *response;

    NSLog(@"%@", response); // Always returns null :(


    if(conn){
        NSLog(@"Connection Successful."); // Connection is successful in my tests.
    }else{
        NSLog(@"Connection could not be made");
    }
}

Here is the NSURLConnectionDelegate delegate implemented in my .h file:

@interface AddTaskViewController : UIViewController <UITextFieldDelegate, UIPickerViewDelegate, NSURLConnectionDelegate>

Can anyone see what I am doing wrong here? The server should return a JSON string, (and it does when I test the web service via my browser) but the NSURLResponse is constantly null.

Thanks,

Peter

Was it helpful?

Solution

Using initWithRequest:delegate: of NSURLConnection starts an asynchronous download, so it returns immediately and executes straight away.

response is always nil because you just defined it and then logged it without ever setting it to anything. That needs to be done in the connection:didReceiveResponse: delegate method.

Where you do if(conn){, the conn existing doesn't mean the connection was successful, it just means that the connection could be created (basically, you didn't supply an invalid request). You don't know whether it's going to work yet.

Implement the delegate methods from NSURLConnectionDelegate_Protocol (and NSURLConnectionDataDelegate) to get access to the response and downloaded data (when it becomes available).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top