ios - 将文件从主包复制到文档目录(沙箱)

标签 ios filepath appstore-sandbox mainbundle documentsdirectory

我需要在第一次运行我的应用程序时将一些 png 从主包复制到文档文件夹。我需要它,因为我必须将这些图像的文件路径保存在核心数据实体中。

我试过了,但是不行,有人知道为什么吗?

// to copy image from main bundle to documents folder

NSString* mainBundleFilePath = [[NSBundle mainBundle] pathForResource:@"SbriciolataDiRicotta" ofType:@"png"];

NSArray *destPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [destPath objectAtIndex:0];

 NSData *mainBundleFile = [NSData dataWithContentsOfFile:mainBundleFilePath];
[[NSFileManager defaultManager] createFileAtPath:documentsDirectory
                                        contents:mainBundleFile
                                      attributes:nil];

// to save the file path

NSString*nomeImmagine = [[NSString alloc] initWithFormat:@"SbriciolataDiRicotta"];
NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@.png",documentsDirectory, nomeImmagine];

谢谢

最佳答案

createFileAtPath 期望将要创建的文件 的路径作为参数,而不是路径 封闭的目录

备注:

  • 您也可以使用 copyItemAtPath:toPath:error: 来复制文件而不加载 全部内容存入内存。
  • 不需要使用 initWithFormat 来分配常量字符串。
  • stringByAppendingPathComponent: 是附加路径组件的正确方法。

关于ios - 将文件从主包复制到文档目录(沙箱),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17542403/

相关文章:

ios - 将文本框值发送到 UILabels

macos - Mac OSX 沙箱和公钥

ios - 我可以在沙盒 macOS 应用程序中使用 Peertalk 或 usbmuxd 吗?

python - 如何使用 sys.path.append 在 python 中导入文件?

java - 从项目目录中的文件夹中读取文件

macos - 如何在 Mac 沙盒应用程序上保留文件或文件夹列表?

ios - Fabric 回答舍入 Int 值

ios - Core Data 在 iPhone4 等旧设备上速度很慢

iphone - 判断 NSManagedObject 属性是否可选

ios - 检查 NSString 是否为本地文件