3

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

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

第一种方法

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

我花了几个小时寻找解决方案,这里的任何帮助将不胜感激。

谢谢你

舒迈斯·乌尔哈克

4

1 回答 1

2

我通过改变它用第二种方法完成了它。不需要创建目录,因为 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];
于 2010-07-26T02:40:25.840 回答