花时间将图像从 URL 加载到 UIImageview

Taking time to load the image from URL to UIImageview(花时间将图像从 URL 加载到 UIImageview)

本文介绍了花时间将图像从 URL 加载到 UIImageview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码将图像从 URL 显示到 UIImageview

I am using this code for displaying the image from URL to 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 中显示图像需要很长时间.

But the problem is that its taking too long time to display the image in imageview.

请帮帮我...

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

Is there any method to fast the process...

推荐答案

我自己的问题给我的答案了解 GCD 块内 [NSData dataWithContentsOfURL:URL] 的行为 确实有意义.所以请确保如果您使用 [NSData dataWithContentsOfURL:URL] 在 GCD 中(就像现在许多开发人员所做的那样)不是下载文件/图像的好主意.所以我倾向于下面的方法(你可以使用 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 防止一次又一次地下载相同的图像.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:花时间将图像从 URL 加载到 UIImageview