我一直在尝试使用NSFileManager将图像缓存到沙盒应用程序的Cache目录中。不幸的是,我的代码似乎不起作用。

- (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。其次,获取我的应用程序的缓存目录的相对路径。第三,附加文件名(这里我只是写了test)。第四,将我的图像转换为NSData。第四,将NSData对象写入指定的路径。

编辑:添加了if语句,用于检查imageData是否为nil

最佳答案

尝试这个:

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");
}

关于ios - NSFileManager不保存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12241745/

10-10 20:58