Search code examples
iosobjective-cnsstringnsdata

Converting NSData to NSString in NSURLConnection = null


I'm sending data to the server and it is responding to my request and I'm getting a text as shown below in the web... Where would be my issue in NSString* newStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; it is not responding to my NSData while there is data in responseData.

My response message:

{ret:0,msg:"<B>Your request has submitted</B><br/>Your request number is 123 <br/>Have a nice day.<br/>"}

My code:

    NSString *link = @"http://example.jsp";

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"first_name=%@&last_name=%@&phone=%@", link, nameField.text, surnameField.text, phoneField.text]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];

NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

NSLog(@"responseData: %@", responseData);

NSString* newStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

NSLog(@"Finish %@", newStr); // newStr is null!!

UIAlertView *message = [[UIAlertView alloc] initWithTitle:title
                                                  message:newStr
                                                 delegate:self
                                        cancelButtonTitle:@"OK"
                                        otherButtonTitles:nil];
[message show];

Solution

  • Your url variable is likely already nil since your string (first_name=…) is not a valid URL: it doesn't even have a scheme and no host.

    I bet if you look closely, Xcode is showing a warning that your format has three placeholders (%@) but you're passing four arguments. What you probably really want to do is something like;

    [NSString stringWithFormat:@"%@?first_name=%@&last_name=%@&phone=%@", link, nameField.text, surnameField.text, phoneField.text]
    

    (Note the additional %@? at the start.)

    In a comment you mention that you do receive data (so your code is just a dummy?). If your call [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] returns nil it means your responseData is something that is not UTF-8 (which is quite a feat, I have never seen that method fail; I did get garbage back, but never nil). The part you're citing looks pretty normal, though: it decodes to \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n{ret:0,msg:"<B>Y.