Подтвердить что ты не робот

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

EDIT: SOLVED

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

Итак, используя этот код (также ниже): 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);
        }
    }
    

    }

======================== END EDIT

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 ;
}
4b9b3361

Ответ 1

Я взял на себя смелость редактировать некоторые из кода, который, как мне кажется, нуждается в небольшом обслуживании. Вы используете устаревшие методы, слишком сложные методы и просто смешные if-elses. Я бы, конечно, проверял, что ваш путь к файлу действителен, не имея представления о том, что такое файл .gallery, и не пытайтесь предоставить фиктивный код, единственное, что я могу сделать, это то, что ваш путь к файлу просто недействителен, потому что ресурс не работает Там, где вы думаете, это так. (В какой-то момент вы попросите скопировать файл в каталог документов, затем проверьте, существует ли он в вашем комплекте!)

    -(void)testMethod {

    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 {
        //simplified method with more common and helpful method 
        resourceDBFolderPath = [[NSBundle mainBundle] pathForResource:@"plans" ofType:@"gallery"];

        //fixed a deprecated method
        [fileManager createDirectoryAtPath:documentDBFolderPath withIntermediateDirectories:NO attributes:nil error:nil];

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

        //check if destinationFolder exists
        if ([ fileManager fileExistsAtPath:documentDBFolderPath])
        {
            //FIXED, another method that doesn't return a boolean.  check for error instead
            if (error)
            {
                //NSLog first error from copyitemAtPath
                NSLog(@"Could not remove old files. Error:%@", [error localizedDescription]);

                //remove file path and NSLog error if it exists.
                [fileManager removeItemAtPath:documentDBFolderPath error:&error];
                NSLog(@"Could not remove old files. Error:%@", [error localizedDescription]);
                return;
            }
        }
    }
}