【问题标题】:NSFileManager Not SavingNSFileManager 不保存
【发布时间】:2012-09-03 03:46:30
【问题描述】:

我一直在尝试使用 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对象写入指定路径。

edit: 添加 if 语句用于检查 imageData 是否为 nil

【问题讨论】:

  • 检查你是否得到了 imageDatacheck 如果你得到的是 imageData= nil
  • 刚刚尝试过,但 imageData 不为零。谢谢你的建议!

标签: ios nsfilemanager


【解决方案1】:

试试这个:

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

【讨论】:

  • 该死,还是不行。我开始对文件写入权限持怀疑态度。我会很快检查的。
  • 您正在检查设备。另请检查文件写入权限
  • 检查我编辑的答案。它现在在重组代码后工作。
  • 它正在工作!我检查了文件夹,它确实在创建文件。感谢您的耐心等待!如果您不介意我问,我查看了这些更改,并不清楚究竟是什么引发了这个问题:您介意简要解释一下吗?再次感谢您!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 2012-09-24
  • 2012-05-23
  • 1970-01-01
  • 1970-01-01
  • 2019-07-04
相关资源
最近更新 更多