本文介绍了花时间将图像从URL加载到UIImageview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我使用此代码显示从URL到UIImageview的图像I am using this code for displaying the image from URL to UIImageviewUIImageView *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中显示图像。But the problem is that its taking too long time to display the image in imageview.请帮帮我......Please help me...有没有办法加快这个过程......Is there any method to fast the process...推荐答案在我自己的问题上给出的答案 了解[NSData dataWithContentsOfURL:URL]在GCD块内的行为 确实有意义。所以如果你使用 [NSData dataWithContentsOfURL:URL] (这些天开发人员做的很多)下载文件/图像并不是一个好主意。所以我倾向于以下方法(您可以使用 NSOperationQueue )。The answers given to me on my own question Understanding the behaviour of [NSData dataWithContentsOfURL:URL] inside the GCD block does makes sense.So be sure that if you use [NSData dataWithContentsOfURL:URL] inside the GCD(as many developers do these days) is not a great idea to download the files/images.So i am leaning towards the below approach(you can either use NSOperationQueue).使用 [NSURLConnection sendAsynchronousRequest:queue]加载图像:completionHandler:然后使用NSCache来阻止下载s ame image一次又一次。Load your images using [NSURLConnection sendAsynchronousRequest:queue:completionHandler: then use NSCache to prevent downloading the same image again and again.正如许多开发人员所建议的那样,去 SDWebimage ,它确实包含了下载图像文件的上述策略。您可以加载任意数量的图像,并且根据作者不会多次下载相同的URL代码As suggested by many developers go for SDWebimage and it does include the above strategy to download the images files .You can load as many images you want and the same URL won't be downloaded several times as per the author of the code 编辑: 上的示例[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}]; 这篇关于花时间将图像从URL加载到UIImageview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-27 11:20