我试图从网页缓存图像,以防止过多的网络请求,以节省电池和数据。其基本思想是:iOS - 缓存远程图像
- 生成该文件的位置
- 的字符串如果该文件存在,那么从文件加载
- 如果它不存在(TODO:或者如果该文件是不是旧的一天),然后从网上下载图像。保存并加载它。
但是我的代码不工作,我不明白为什么?
// 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];
}
在哪种情况下你有麻烦?从读取缓存或写入缓存? – l0gg3r 2014-10-22 09:22:12
你的'if'语句检查'iconPath'是否存在,但我认为你的意思是'imagePath'?你的'NSData'调用然后从'imagesURL'创建一个URL,我认为它应该是'imagePath'。另外,如果你正在缓存数据,你应该把它放在'Library/Caches'文件夹('NSCachesDirectory')中,这样操作系统可以在空间不足时删除这些数据,因为它可以被你的应用程序重新下载。将其放置在Caches文件夹中也可以确保它不会被iTunes和iCloud自动备份。 – ttarik 2014-10-22 09:29:09
@ ev0lution我改变了iconPath到imagePath,那只是一个错字。 imageURL引用Web上的URL来抓取图像,而imagePath引用保存的(缓存的)文件位置。我如何获取应用程序的缓存目录? – dgee4 2014-10-22 11:25:45