【发布时间】:2014-12-17 16:33:42
【问题描述】:
我正在尝试缓存来自网络的图像,以防止过多的网络请求以节省电池和数据。基本思路是:
- 生成文件位置字符串
- 如果文件存在,则从文件中加载它
- 如果它不存在(待办事项:或者如果文件超过一天),则从网络下载图像。保存并加载它。
但是我的代码不起作用,我不知道为什么?
// imagesFileName has been correctly generated as as imageURL
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagesLibraryPath = [documentsDirectory stringByAppendingPathComponent:@"Images"];
NSString *imagePath = [imagesLibraryPath stringByAppendingPathComponent:imageFileName];
// Do We Have the icon in cache?
if (![[NSFileManager defaultManager] fileExistsAtPath:iconPath]) {
// File Doesn't Exist - Load Image From URL
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imagesURL]];
// Save Image
[imageData writeToFile:imagePath atomically:YES];
NSLog(@"Downloading & Importing Image");
return [UIImage imageWithData:imageData];
} else {
// Load the Image From The File But Update If Needed
NSLog(@"Loading Image From Cache");
return [UIImage imageWithContentsOfFile:imagePath];
}
【问题讨论】:
-
在哪种情况下您遇到了麻烦?从读缓存,还是写缓存?
-
您的
if语句检查iconPath是否存在,但我认为您的意思是imagePath?然后您的NSData调用会从imagesURL创建一个URL,我认为它应该是imagePath。此外,如果您正在缓存数据,则应将其放在Library/Caches文件夹 (NSCachesDirectory) 中,以便操作系统可以在空间不足时删除这些数据,因为它可以由您的应用程序重新下载。将它放在 Caches 文件夹中还可以确保它不会被 iTunes 和 iCloud 自动备份。 -
@ev0lution 我已将 iconPath 更改为 imagePath,这只是一个错字。 imageURL 是指 Web 上从中获取图像的 URL,而 imagePath 是指保存(缓存)文件的位置。如何获取应用的缓存目录?
-
@dgee4 使用
NSCachesDirectory而不是NSDocumentDirectory来查找Caches 目录。
标签: ios objective-c nsurl nsdocumentdirectory