我正在尝试编写异步图像下载程序。我使用NSURLConnection将数据导入NSMutableData,并在完成初始化UIImage后使用该数据。
我检查了字节,然后正确地下载了整个图像(至少是正确的字节数);当我打电话
[UIImage imageWithData:data]
然后检查图像的属性,它是零宽度和高度的垃圾数,实际上,无论图像是什么,都是相同的数字。我尝试了一堆不同的图像,png,jpg,不同的网址,它总是完全下载图像,但UIImage无法初始化该数据。我在这里做错了什么?
感谢。
代码真的如你所期望的那样:
连接代表:
-(void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
[[ImageManager sharedInstance] dataDownloadedBy:self]; }
的ImageManager:
-(void)dataDownloadedBy:(WebConnection *)connection{
WebImage *image = [[WebImage alloc] initWithLink:connection.url];
[image setImageFromData:connection.data];
[images addObject:image];
[connection release];}
WebImage:
-(void)setImageFromData:(NSMutableData *)data{
image = [[UIImage alloc] initWithData:data];}
答案 0 :(得分:2)
首先,我确定UIImage不会使用垃圾数据进行初始化。构造函数 initWithData
分析数据以确定文件格式。如果您的数据已损坏,则返回的图像将为零。首先检查一下。
-(void)dataDownloadedBy:(WebConnection *)connection{
WebImage *image = [[WebImage alloc] initWithLink:connection.url];
[image setImageFromData:connection.data];
if (image.image != nil) { [images addObject:image]; }
[connection release];
}
其次,请确保在下载过程中附加数据。这是回调方法:
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.receivedData appendData:data];
}
最后,您的代码必须绝对包含第二种情况:下载失败。
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
}
您的问题描述缺少一些重要的代码。
Apple的URLCache演示是了解异步图像下载的一个非常好的项目。 http://developer.apple.com/iphone/library/samplecode/URLCache/Introduction/Intro.html
我希望这会对你有所帮助!
答案 1 :(得分:0)
我不知道有什么问题,可能是你没有正确使用发布,说我不知道为什么你在dataDownloadedBy结束时释放连接,它应该是图像? 如果你在这里发布更多代码,它会有所帮助。
我曾经做过同样的事情,你可以看看这里的帖子 http://blog.163.com/lionyue@126/blog/static/1079307120096895433277/
希望有所帮助
答案 2 :(得分:0)
如果initWithData失败,很可能您获得的图像数据已损坏。你应该将它保存到这样的文件:
[data writeToFile:@"/tmp/foo.jpg" atomically:NO];
然后尝试在Preview.app中打开它。
答案 3 :(得分:0)
一个不同的问题,但是如果你要求一个无法访问的文件,那就会产生同样的痛苦错误:HTTP服务器会回复错误404消息,你的代码会读取该字节(它们不是图像的有效字节,你会得到NIL。