如何从服务器异步检索图像 [英] How to retrieve images from server asynchronously

查看:81
本文介绍了如何从服务器异步检索图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSMutableArray,带有一些图像URL.图像的大小在12KB至6MB之间.我使用AsycImageView类并实现,但是当下载大图像时应用程序崩溃时,我在该类中为maxsize分配了6 * 1024 * 1024(6MB),将时间间隔60.0秒增加到180.o秒,但是没有用.我收到错误消息接收到内存警告",当应用程序崩溃时,连接自动从设备中删除,但在模拟器中没有崩溃.

i have one NSMutableArray with some image url's. The images have sizes between 12KB to 6MB. I use AsycImageView class and implement but when large images are downloading application get crashed, I gave 6*1024*1024 (6MB) for maxsize in that class, increase time interval 60.0 sec to 180.o sec, but there is no use. I'm getting an error "Received memory warning" and when app crash automatically connection remove from device, but in simulator there is no crash.

推荐答案

,您可以使用multiThreading进行此操作.这是代码

you can do this using multiThreading. Here is a code

- (UIImageView *)getImageFromURL:(NSDictionary *)dict
{
    #ifdef DEBUG
    NSLog(@"dict:%@", dict);
    #endif

    UIImageView *_cellImage = nil;
    _cellImage = ((UIImageView *)[dict objectForKey:@"image"]);
    NSString *strURL = [dict objectForKey:@"imageurl"]);

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];

    #ifdef DEBUG
    NSLog(@"%i", data.length);
    #endif

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataFilePath = [NSString stringWithFormat:@"%@.png", [documentsDirectory stringByAppendingPathComponent:[dict objectForKey:@"imageid"]]];

    if (data) // i.e. file exist on the server
    {
        [data writeToFile:dataFilePath atomically:YES];
        _cellImage.image = [UIImage imageWithContentsOfFile:dataFilePath];
    }
    else // otherwise show a default image.
    {
        _cellImage.image = [UIImage imageNamed:@"nouser.jpg"];
    }
    return _cellImage;
}

并像这样在cellForRowAtIndexPath中调用此方法:

And call this method in cellForRowAtIndexPath like this:

    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:imageURL, @"imageurl", self.imgPhoto, @"image", imageid, @"imageid", nil];
    [NSThread detachNewThreadSelector:@selector(getImageFromURL:) toTarget:self withObject:dict];

该代码将开始在多个线程中获取图像,并将图像本地保存到文档文件夹中.如果已存在相同名称的图像,则该图像也不会再次下载.希望对您有帮助

The code will start getting images in multiple threads and will save image locally to document folder. Also the image will not download again if already exists with the same name. Hope this helps

这篇关于如何从服务器异步检索图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆