如何将URL图像存储在缓存中,然后在iphone中的imageview中显示

时间:2013-03-08 10:34:23

标签: iphone ios ios4

我在Imageview中直接打开URL图像,但我想将图像存储在缓存中以备将来参考...帮我解决问题..

提前致谢

3 个答案:

答案 0 :(得分:5)

您可以使用SDWebImage使用图片缓存...

此库为UIImageVIew提供了一个类别,支持来自网络的远程图像。

它提供:

将{1}类别添加到Cocoa Touch框架

的Web图像和缓存管理

异步图片下载器

具有自动缓存到期处理的异步内存+磁盘映像缓存

背景图片解压缩

保证不会多次下载相同的网址

保证不会一次又一次地重试虚假网址

保证主线程永远不会被阻止

性能! 使用GCD和ARC

答案 1 :(得分:0)

这是iOS开发中的一个经典问题,之前我写了一个类OnlineImageView,它正在使用NSOperationQueue - 现在GCD可能更好。

您想访问在线图片:

  1. 首先,您尝试在图像中点击图像(使用密钥,可能是网址) 内存缓存,但错过了。
  2. 其次,你试图找到磁盘中的图像,再次错过。
  3. 然后,您应该使用GCD异步下载在线图像 或其他一些方法。
  4. 成功下载图像后,将其显示在 UIImageView,并将其缓存在内存中,将其写入磁盘 供将来使用。
  5. 一些示例代码:

    - (void)downloadImage:(NSDictionary *)info
    {
        /* HOWTO: Prevent Downloading the same url many times */
        /* Keep the download task one by one ? */
    
        NSString *url = [info objectForKey:@"url"];
        NSURL *imageUrl = [NSURL URLWithString:url];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
    
        if (image) {
            id theDelegate = [info objectForKey:@"delegate"];
            if ([theDelegate respondsToSelector:@selector(imageDownloader:didFinishWithImage:)]) {
                [theDelegate imageDownloader:self didFinishWithImage:image];
            }
    
            [cacheQueue cacheImage:image withKey:url];
        } else {
    #ifdef DEBUG
            NSLog(@"Failed to download : %@\n", url);
    #endif
        }
    }
    

答案 2 :(得分:0)

使用SDWebImage。它最好,最容易用于图像数据缓存。