Question

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.

Was it helpful?

Solution

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top