gpt4 book ai didi

iPhone : Unable to copy from MainBundle to NSDocumentDirectory

转载 作者:行者123 更新时间:2023-12-03 20:00:59 26 4
gpt4 key购买 nike

我正在尝试将几个图像文件从 MainBundle/SampleImages 文件夹复制到应用程序 NSDocumentDirectory/Library 文件夹,但无法执行此操作。我已检查图像是否位于 .app/Mainbundle/SampleImages 目录中,并且还检查了是否在 NSDocumentsDirectory 中创建了 Library 文件夹,但没有复制任何文件。

我尝试了下面给出的两种方法,但没有成功。这是我用来复制文件的代码。

第一种方法

NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentLibraryFolderPath = [documentsDirectory stringByAppendingPathComponent:@"Library"];

NSString *resourceSampleImagesFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"SampleImages"];
NSData *mainBundleFile = [NSData dataWithContentsOfFile:resourceSampleImagesFolderPath];
[[NSFileManager defaultManager] createFileAtPath:documentLibraryFolderPath
contents:mainBundleFile
attributes:nil];

第二种方法

NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentSampleImagesFolderPath = [documentsDirectory stringByAppendingPathComponent:@"Library"];

NSString *resourceSampleImagesFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"SampleImages/"];
[fileManager createDirectoryAtPath: documentSampleImagesFolderPath attributes:nil];
if([fileManager copyItemAtPath:resourceSampleImagesFolderPath toPath:documentSampleImagesFolderPath error:&error]) {
NSLog(@"success");
}
else {
NSLog(@"Failure");
NSLog(@"%d",error);
}

我花了几个小时寻找解决方案,如果您能提供任何帮助,我们将不胜感激。

谢谢

舒迈斯·乌尔·哈克

最佳答案

我用第二种方法通过稍微改变一下就完成了。不需要创建目录,因为 SDK 文档说目标目录必须不存在。

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentDBFolderPath = [documentsDirectory stringByAppendingPathComponent:@"Library"];

NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:@"SampleImages"];
[fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error];

关于iPhone : Unable to copy from MainBundle to NSDocumentDirectory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3331812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com