获取 SDWebImage 缓存图像

Get SDWebImage Cache Image

请问SDWebImageManager下载后如何获取下载的图片。我只有通过 URL 下载它的代码,这是我得到的:

let manager: SDWebImageManager = SDWebImageManager.sharedManager()
                        manager.downloadImageWithURL(NSURL(string: feedDetails.thumbnail), options: [],
                            progress: {(receivedSize: Int, expectedSize: Int) -> Void in
                                print(receivedSize)
                            },
                            completed: {(image, error, cached, finished, url) -> Void in

                                self.feedImage.image = image
                            }
                        )

来自SDWebImageManagerclassdownloadImageWithURL:方法

Downloads the image at the given URL if not present in cache or return the cached version otherwise.

因此,如果图像存在于缓存中,您已经使用代码检索它,而不是从 Web 下载。

据我所知(我刚刚看了作者的Git页面)有以下方法可以直接访问存储在缓存中的图像-

您可以使用 SDImageCache 通过以下代码将图像显式存储到缓存中:

[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];

其中 myImage 是您要存储的图像,myCacheKey 是图像的唯一标识符。

将图像存储到缓存中并想使用该图像后,只需执行以下操作:

[[SDImageCache sharedImageCache] queryDiskCacheForKey:myCacheKey done:^(UIImage *image) {
    // image is not nil if image was found
}];

此代码为Objective-C代码,您必须"convert"自己swift。

希望能帮到你!

感谢@beef 的回答,但是 SDWebImage 已经更新了部分代码: 保存图像:

 [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:string] options:SDWebImageDownloaderUseNSURLCache progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {

        if (image && finished) {
            // Cache image to disk or memory

            [[SDImageCache sharedImageCache] storeImage:image forKey:@"img_key" toDisk:YES completion:^{
                //save
            }];
        }
    }];

从磁盘缓存中获取图像:

 [[SDImageCache sharedImageCache] queryCacheOperationForKey:@"img_key" done:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
        [self.imageV setImage: image];
    }];