mM app从我的Parse.com后端下载一些新图像。示例代码:
//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…
}
}
但是我注意到如果连接出现问题或某种一般性错误,将下载图像(没有错误),但图像会因黑色锯齿线而失真而不完整。有没有办法检查下载的图像是否完整无损并且没有失真?
答案 0 :(得分:0)
之前我也有这个问题,我检查一个标题并将Content-Length与完成下载的数据进行比较。
如果Web服务器正常工作并且可以返回Content-Length的正确响应,您可以使用它来检查数据。
以下是仅下载请求标头的代码段:
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.
}
您也可以将它与NSHTTPURLResponse一起使用,用于下载图像以保存HTTP请求。
接下来是获取NSData的长度。您可以使用方法:
NSUInteger dataLength = [downloadedData length];
然后比较两个值,如果两个长度相等,则下载完成,否则您需要重新下载。
您还可以通过读取Content-Type标头检查图像是否已损坏,并检查数据的第一个和最后一个字节。
对于PNG How to check if downloaded PNG image is corrupt? 不要忘记施放"字节"到" char",无论如何你都会看到警告。
适用于JPEG Catching error: Corrupt JPEG data: premature end of data segment
希望这可以帮到你。 :)