2013-08-29 33 views
1

我使用这个代码从URL显示图像的UIImageView花时间从URL加载图像到UIImageView的

UIImageView *myview=[[UIImageView alloc]init]; 

myview.frame = CGRectMake(50, 50, 320, 480); 

NSURL *imgURL=[[NSURL alloc]initWithString:@"http://soccerlens.com/files/2011/03/chelsea-1112-home.png"]; 

NSData *imgdata=[[NSData alloc]initWithContentsOfURL:imgURL]; 

UIImage *image=[[UIImage alloc]initWithData:imgdata]; 

myview.image=image; 

[self.view addSubview:myview]; 

但问题是,它花费太长时间的ImageView来显示图像。

请帮我...

有没有快速的过程方法...

+0

你怎么能指望合作当所有这取决于所使用的网络的强度时,可以更快地下载数据。 – AppleDelegate

+0

您可以使用GCD作为建议的其他答案,但这将同样缓慢,它不会冻结应用程序。 –

+0

我花了大约3秒钟来加载图像。您是一次只载入一张图片,还是有更多的下载在paralell中运行?你可以使用一些更快的图像下载服务?是加载一个较小的图像文件(像素较小的尺寸)的选项?你能切换到hgihly压缩的JPEG?你可以使用一个框架来启用一些缓存(我不认为NSData会这样做)。这是一个选择吗?含义:你是否一次又一次加载相同的图像? –

回答

1

给我对我自己的问题的答案Understanding the behaviour of [NSData dataWithContentsOfURL:URL] inside the GCD block没有品牌sense.So可以肯定,如果你使用的[NSData dataWithContentsOfURL:URL] GCD内(如许多开发商做的这些天)是不是一个好主意,下载的文件/图片所以我倾向于下面的方法(你可以使用NSOperationQueue)。

使用[NSURLConnection sendAsynchronousRequest:queue:completionHandler:加载图像,然后使用NSCache来防止一次又一次下载相同的图像。

至于建议由许多开发者去SDWebimage,它并包括上述策略下载图像文件。你可以加载你想尽可能多的图像和相同的URL将不被下载多次按作者代码

编辑的:

例如在[NSURLConnection sendAsynchronousRequest:queue:completionHandler:

NSURL *url = [NSURL URLWithString:@"your_URL"]; 
NSURLRequest *myUrlRequest = [NSURLRequest requestWithURL:url]; 
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 
[NSURLConnection sendAsynchronousRequest:myUrlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
{ 

    if ([data length] > 0 && error == nil) 
     //doSomething With The data 

    else if (error != nil && error.code == ERROR_CODE_TIMEOUT) 
     //time out error 

    else if (error != nil) 
     //download error 
}]; 
1
Use Dispatch queue to load image from URL. 


dispatch_async(dispatch_get_main_queue(), ^{ 

    }); 

Or add a placeholder image till your image gets load from URL. 
+0

你仍然需要担心缓存和其他一切。只是使用https://github.com/AndreyLunevich/DLImageLoader-iOS/tree/master/DLImageLoader – Fattie

2

相反dispatch_async的,使用SDWebImage来缓存图像。

这是最好的我见过...

dispatch_async的问题是,如果你失去了重心从形象,它会再次加载。但SDWebImage缓存图像,并且不会再次重新加载。

+0

这很好,但GDImageLoader是令人难以置信的简单,坚实 - 这是最好的.. https://github.com/AndreyLunevich/DLImageLoader-iOS/tree/master/DLImageLoader没有手册,没有学习曲线 - 一个命令。非常棒。 – Fattie

+0

示例... http://stackoverflow.com/a/19115912/294884 – Fattie