0

I'm having a strange problem reading a response from an api. In connectionDidFinishLoading, when logging the response as a string [NSString stringWithUTF8String:[self.response bytes]], the string sometimes is logged correctly, sometimes is null, and other times is the correct response with random characters appended at the end.

In didReceiveData, the response is fine, but the problem occurs after using appendData. In didReceiveData I can illustrate the problem like this:

// This is always 0
NSLog(@"data length is %i", [data length]);
// This is always the correct response string sent from the api
NSLog(@"data string is %@", [NSString stringWithUTF8String:[data bytes]]);

NSMutableData *foo = [[NSMutableData alloc] init];
[foo appendData:data];

// This is always 8
NSLog(@"foo length is %i", [foo length]);
// This is only sometimes the correct response string!
NSLog(@"foo string is %@", [NSString stringWithUTF8String:[foo bytes]]);

[foo release];
foo = nil;

I've seen a couple other questions on SO about similar crazy problems with appendData, but they seem to have been because the variable being appended to was nil. This shows that I've clearly declared my NSMutableData foo, but it's still not correctly being set.

Justin McCandless
  • 621
  • 1
  • 10
  • 20
  • 2
    stringWithUTF8String will assume that bytes are in utf8. that may not give correct results. Fabian Kreiser's answer is better approach. – Mohammad Feb 28 '13 at 07:13

1 Answers1

2

Please post the whole code and not just this short excerpt.

I assume that you're reallocating a new NSMutableData instance each time -connection:didReceiveData: is called. You need to use a property or an iVar for that so that the data is appended to the already existing data when -connection:didReceiveData: is called subsequent times.

- (void)startConnection
{
    self.receivedData = [[NSMutableData alloc] init];
    // Start connection...
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)
{
    NSString *receivedString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
    self.receivedData = nil;

    NSLog(@"Response: %@", receivedString);
}
Fabian Kreiser
  • 8,307
  • 1
  • 34
  • 60
  • Sorry, thought narrowing it down would help. My method of converting to a string was the problem, yours fixed it. – Justin McCandless Feb 28 '13 at 07:33
  • So for posterity, get the string from the data with this `[[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]` not with this `[NSString stringWithUTF8String:[self.receivedData bytes]]`. Thank you! – Justin McCandless Feb 28 '13 at 07:43