缓存图像以供脱机SDWebImage使用

时间:2016-10-14 09:26:27

标签: ios swift uiimageview sdwebimage

我正在使用SDWebImage下载来自不同网址的图片,现在我想知道是否可以下载这些图片将它们存储在哪里,所以当我离线并启动我的应用程序时,我仍然可以看到它们?< / p>

我注意到Instagram使用了类似的东西,一旦你下载了图像,就可以关闭应用程序离线,然后重新打开应用程序,你仍然可以看到图像。

我认为这可以通过SDWebImage实现,但不确定,如果不可能,请纠正我。

非常感谢任何有帮助的人!

3 个答案:

答案 0 :(得分:1)

导入UIImageView+WebCache.h标头,并在viewcontroller中调用 setImageWithURL:placeholderImage:方法。将为您处理SDWebImage lib,从异步下载到缓存管理。

答案 1 :(得分:1)

我认为你要归档的是那种饲料,你的应用程序被杀死/重新启动之后就会显示4-5张照片,而且你没有互联网连接 - 就像Instagram一样。< / p>

您有可能下载图像,因为您已经习惯了互联网连接并将4-5张图像存储到核心数据中作为NSData。

然后你可以使用这些图像作为占位符,你会有&#34;内容&#34;而用户没有连接。

以下是将图像转换为NSData并返回的代码:

let dataFromImage = UIImagePNGRepresentation(image!)!
let imageFromData = UIImage(data: imageData)

这是how to store images into core data.

的完美教程

然后,您可以在reachability == false的情况下使用核心数据中的图像填充tableView(例如)。

答案 2 :(得分:1)

您可以使用SDWebImage将图片存储在应用目录中,而不必手动存储。使用SDImageCache会更简单。 diskImageExistsWithKey通过回调确定您的图像是否存在于位置(目录中或应用程序的临时文件夹中)。您只需检查一下! ...

[[SDImageCache sharedImageCache] diskImageExistsWithKey:localImagePath completion:^(BOOL isInCache) {
        if ( isInCache ) {
            image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:localPath]; // it returns a simple UIImage 
[yourImageView setImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:localPath]]; // or set image in your UIImageView
        } else {
            [yourImageView sd_setImageWithURL:[NSURL URLWithString:downloadPath] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                if (image) {
                    [[SDImageCache sharedImageCache] storeImage:image forKey:localPath toDisk:YES completion:^{ // This block will help you to store image from server to local directiry
                        NSLog(@"Downloaded");
                    }];
                }
            }];
        }
    }] ;