我一直在尝试使用NSFileManager将图像缓存到我沙盒应用的缓存目录中。不幸的是,我的代码似乎不起作用。
- (BOOL)saveImageToCacheFolder
{
NSFileManager *filemgr = [NSFileManager defaultManager];
NSString *cachePath = [[[filemgr URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject] absoluteString];
NSString *fullpath = [cachePath stringByAppendingPathComponent:@"test.jpg"];
NSURL *imageURL = [FlickrFetcher urlForPhoto:self.photoData format:FlickrPhotoFormatLarge];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
BOOL success = false;
if (imageData != nil) {
success = [imageData writeToURL:[NSURL URLWithString:fullpath] atomically:true];
if (!success) NSLog(@"Did Not Managed to save the image");
}
return success;
}
这是我想要做的。首先,获取默认的NSFileManager。其次,获取我的应用程序的缓存目录的相对路径。第三,追加我的文件的名称(这里我刚刚写了测试)。第四,将我的图像转换为NSData。第四,将NSData对象写入指定的路径。
编辑:添加了if语句,用于检查imageData是否为nil
答案 0 :(得分:3)
试试这个:
NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [myPathList objectAtIndex:0];
NSString *fullpath = [cachePath stringByAppendingPathComponent:@"test.jpg"];
NSURL *imageURL = [FlickrFetcher urlForPhoto:self.photoData format:FlickrPhotoFormatLarge];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
if (imageData != nil) {
success = [imageData writeToURL:[NSURL fileURLWithPath:fullpath] atomically:YES];
if (!success) NSLog(@"Did Not Managed to save the image");
}