I am downloading a bitmap using NSURLConnection. I set the delegate to self, and implement the methods connection:didReceiveData and connectionDidFinishLoading. When data is received, I store it in an NSMutableData object (called input), and then at the end of the connection, I use this to create the bitmap. The problem is that I receive the data in connection:didReceiveData but it is null in connection:DidFinishLoading. How do I fix this?
- (void)start
{
NSURL *url = [NSURL URLWithString:src];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:YES];
}
- (void)connection:(NSURLConnection *)conn
didReceiveData:(NSData *)d
{
NSLog(@"Data Received: %@", d);//This prints the correct data
//Add data chunk to input
[input appendData:d];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
CPLog(@"Finished Receiving bitmap from server. Data received with length %d: %@", [input length], input);//this prints length 0 and a value of (null)
CFDataRef imgData = (__bridge CFDataRef) input;
CGDataProviderRef imgDataProvider = CGDataProviderCreateWithCFData (imgData);
CGImageRef image;
if (!imgDataProvider)
{
NSLog(@"Request Failed!");//happens every time
[callback handleBitmap:nil];
return;
}
image = CGImageCreateWithJPEGDataProvider(imgDataProvider, NULL, true, kCGRenderingIntentDefault);
[callback handleBitmap:image];
return;
}
You should allocate memory for
inputproperty. Usually it is done before starting new url connection: