views:

1125

answers:

3

I'm getting an image over HTTP, using NSURLConnection, as follows -

NSMutableData *receivedData;

- (void)getImage {
    self.receivedData = [[NSMutableData alloc] init];
    NSURLConnection *theConnection = // create connection
}

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

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
   [connection release];

   UIImage *theImage = [UIImage imageWithData:receivedData];
}

Usually it works just fine, but sometimes I'm seeing this get logged - : Corrupt JPEG data: premature end of data segment

At this point, the image does not completely render. I'll see maybe 75% of it, and then the lower right hand corner is a grey box.

Any ideas on how to approach fixing this? Am I constructing my image improperly?

+2  A: 

Your HTTP code looks correct. You might want to log the size of the receivedData once it's done loading and compare it to the expected size of the image on the server. If it's the expected size, then maybe the image itself is corrupted on the server.

Marc Novakowski
Thanks, this helped out a lot. By doing this I realized it was my own programming error (I was accidently firing off the request twice).
bpapa
+1  A: 

I have seen this also. If you save the data to a file and then read the data back into an image, it works perfectly. I suspect there is http header information in the jpeg image data.

Hope someone finds a solution to this because the save to file workaround sucks.

// problem

UIImage *newImage = [UIImage imageWithData:receivedData];

// crappy workaround

[receivedData writeToFile:[NSString stringWithFormat:@"a.jpg"] atomically:NO];
UIImage *newImage = [UIImage imageWithContentsOfFile:@"a.jpg"];
Will
A: 

ASI-HTTP can fix this problem.

NSURL *coverRequestUrl = [NSURL URLWithString:imageStringURL];
ASIHTTPRequest *coverRequest = [[ASIHTTPRequest alloc] initWithURL:coverRequestUrl];
[coverRequest setDelegate:self];
[coverRequest setDidFinishSelector:@selector(imageRecieved:)];

[appDelegate.queue addOperation:coverRequest];
[appDelegate.queue go];

My queue variable in appDelegate is ASINetwork queue object. Because I send asynchronous request, so I use it.

- (void)imageRecieved:(ASIHTTPRequest *)response
{
    UIImage *myImage = [UIImage imageWithData:[response responseData]];
}
Jerapong Nampetch