Downloading images from Parse.com and checking the images are not damaged

application

mM downloads some new images from my Parse.com server. Code example:

//Where object is a downloaded PFObject PFFile *image = object[@"image"]; [image getDataInBackgroundWithBlock:^(NSData *data, NSError *error) { if(!error) { UIImage *image = [UIImage imageWithData:data]; //Do more work here… } } 

However, I noticed that if there is a connection problem or some common error, the image will be downloaded (without errors), but the image will be distorted by black jagged lines and will not be completed. Is there a way to check if the downloaded image is completely intact and not distorted?

+5
source share
1 answer

I also have this problem before, I check the header and compare the Content-Length with the data that completes the download.

In case the web server is working correctly and can return the correct answer for Content-Length, you can use it to check the data.

Here is a snippet to download only the request header:

 NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease]; request.HTTPMethod = @"HEAD"; NSHTTPURLResponse *response; [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; if ([response respondsToSelector:@selector(allHeaderFields)]) { NSDictionary header = [response allHeaderFields]; NSString *rawContentLength = [header objectForKey:@"Content-Length"]; NSNumber *contentLength = [NSNumber numberWithInt:[rawContentLength intValue]]; // Convert contentLength to NSUInteger and use to compare with you NSData length. } 

you can also use it with the NSHTTPURLResponse, which you use to upload the image to save the HTTP request.

Next, get the length of the NSData. You can use the method:

 NSUInteger dataLength = [downloadedData length]; 

Then compare both values, if the two lengths are equal, it will load completely, otherwise you will need to reload.

You can also check if the image is corrupted by reading the Content-Type header and checking some of the first and last bytes of the data.

For PNG How to check if the downloaded PNG image is damaged? Do not forget to point the "byte" to "char", you will still see a warning.

For JPEG Tracking Error: Corrupt JPEG Data: Premature End of Data Segment

Hope this can help you. :)

0
source

All Articles