Копировать папку (с содержимым) из комплекта в каталог документов - iOS

РЕДАКТИРОВАТЬ: РЕШЕНО

Спасибо, Брукс. Ваш вопрос заставил меня продолжать копаться, если файл даже существовал в моем комплекте - и это не так!

Таким образом, используя этот код (также ниже): iPhone / iPad: невозможно скопировать папку из NSBundle в NSDocumentDirectory и инструкции для правильного добавления каталога в Xcode (изВот и ниже) мне удалось заставить его работать.

Скопируйте папку в Xcode:

Создайте каталог на своем Mac.Выберите Добавить существующие файлы в ваш проектВыберите каталог, который вы хотите импортироватьВо всплывающем окне выберите «Копировать элементы в папку целевой группы» и «Создать ссылки на папки для всех добавленных папок».Хит "Добавить"

Справочник должен отображаться синим вместо желтого.

-(void) copyDirectory:(NSString *)directory {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentDBFolderPath = [documentsDirectory stringByAppendingPathComponent:directory];
NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:directory];

if (![fileManager fileExistsAtPath:documentDBFolderPath]) {
    //Create Directory!
    [fileManager createDirectoryAtPath:documentDBFolderPath withIntermediateDirectories:NO attributes:nil error:&error];
} else {
    NSLog(@"Directory exists! %@", documentDBFolderPath);
}

NSArray *fileList = [fileManager contentsOfDirectoryAtPath:resourceDBFolderPath error:&error];
for (NSString *s in fileList) {
    NSString *newFilePath = [documentDBFolderPath stringByAppendingPathComponent:s];
    NSString *oldFilePath = [resourceDBFolderPath stringByAppendingPathComponent:s];
    if (![fileManager fileExistsAtPath:newFilePath]) {
        //File does not exist, copy it
        [fileManager copyItemAtPath:oldFilePath toPath:newFilePath error:&error];
    } else {
        NSLog(@"File exists: %@", newFilePath);
    }
}

}

======================== КОНЕЦ РЕДАКТИРОВАНИЯ

FRUs-паразитный-ши-на! Так или иначе...

Приведенный ниже код копирует мою папку из пакета приложения в папку «Документы» в симуляторе. Однако на устройстве я получаю сообщение об ошибке и нет папки. Используя Ze Google, я обнаружил, что ошибка (260) означает, что файл (в данном случае моя папка) не существует.

Что может быть не так? Почему я не могу скопировать свою папку из пакета в Документы? Я проверил, что файлы существуют - хотя папка не отображается - потому что XCode хочет плоский файл? Превратила ли она мою папку (перетаскиваемую в Xcode) в плоский файл ресурсов?

Я благодарю вас за любую помощь.

//  Could not copy report at path /var/mobile/Applications/3C3D7CF6-B1F0-4561-8AD7-A367C103F4D7/cmsdemo.app/plans.gallery to path /var/mobile/Applications/3C3D7CF6-B1F0-4561-8AD7-A367C103F4D7/Documents/plans.gallery. error Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x365090 {NSFilePath=/var/mobile/Applications/3C3D7CF6-B1F0-4561-8AD7-A367C103F4D7/cmsdemo.app/plans.gallery, NSUnderlyingError=0x365230 "The operation couldn’t be completed. No such file or directory"}

NSString *resourceDBFolderPath;

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

if (success){
    NSLog(@"Success!");
    return;
} else {
    resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath]
                                      stringByAppendingPathComponent:@"plans.gallery"];
    [fileManager createDirectoryAtPath: documentDBFolderPath attributes:nil];
    //[fileManager createDirectoryAtURL:documentDBFolderPath withIntermediateDirectories:YES attributes:nil error:nil];

    [fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath           
                          error:&error];
}

    //check if destinationFolder exists
if ([ fileManager fileExistsAtPath:documentDBFolderPath])
{
    //removing destination, so source may be copied
    if (![fileManager removeItemAtPath:documentDBFolderPath error:&error])
    {
        NSLog(@"Could not remove old files. Error:%@",error);
        return;
    }
}
error = nil;
//copying destination
if ( !( [ fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error ]) )
{
    NSLog(@"Could not copy report at path %@ to path %@. error %@",resourceDBFolderPath, documentDBFolderPath, error);
    return ;
}

Ответы на вопрос(1)

Ваш ответ на вопрос