I have followed a handful of examples on NSURLConnection, see latest below, but yet I keep getting null on the returned FinishLoading. I checked didReceiveResponse and its getting the data. What am I not doing right here?
EDITED: Now works as expected.
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_dataDictionary = [NSMutableDictionary new];
_theReceivedData = [NSMutableData new];
[_theReceivedData setLength:0];
// add object
[_dataDictionary setObject:_theReceivedData forKey:[connection description]];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableData *imageData = _dataDictionary[ [connection description] ];
[imageData appendData:data];
if([connection description]!=nil && imageData!=nil)
{
[_dataDictionary setObject:imageData forKey:[connection description]];
}
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
NSData *imageData = _dataDictionary[ [connection description] ];
if(imageData!=nil)
{
NSLog(@"%@",imageData);
Take NSMutableData *theReceivedData out. Make it a class variable. Your problem is theReceivedData
is being deallocated in every method. You are creating a new object in every method. Retain the old one.
NSMutableData *_theReceivedData;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_theReceivedData = [NSMutableData new];
[_theReceivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_theReceivedData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
// LOOK AT THIS http://stackoverflow.com/questions/1064920/iphone-corrupt-jpeg-data-for-image-received-over-http
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"%@",_theReceivedData);