如何使用文件名将图像缓存到 Caches 文件夹中。我有一个来自互联网的 Collection View 加载图像 url。所以我想在 Caches 文件夹中缓存文件名为 url 的图像。提前致谢
最佳答案
下载图像并将其保存到缓存文件夹非常简单:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSString *urlString = @"http://URL";
NSData *webData= [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
if (webData) {
// save in the Filesystem
NSString* cachesDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *file = [cachesDirectory stringByAppendingPathComponent:[urlString lastPathComponent]];
[webData writeToFile:file atomically:YES];
}
});
但是当您显示图像时,ios 使用惰性图像解压缩,这会在主线程上产生延迟。为了避免这些延迟,有很棒的库:
我建议您使用其中之一。
关于ios - 如何使用来自url的文件名将图像缓存到文档文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24613516/