Запустите NSBundle из папки документов - PullRequest
0 голосов
/ 24 февраля 2011

Есть ли способ использовать NSBundle из папки документов на iOS?

Ответы [ 2 ]

8 голосов
/ 24 августа 2011

Не знаю точно, каков точный вопрос, но вот как я получаю доступ к локальной папке документов моего приложения (это не папка документов, в которой вы храните источники, используемые вашим приложением, а та, в которой ваше приложение хранит локальные ресурсы) например, в своем приложении я снимаю фотографии с камеры и сохраняю их в локальной папке приложения, а не в списке устройств, поэтому для получения количества изображений, которые я делаю, в методе viewWillAppear используйте:

// create the route of localDocumentsFolder
NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//first use the local documents folder
NSString *docsPath = [NSString stringWithFormat:@"%@/Documents", NSHomeDirectory()];
//then use its bundle, indicating its path
NSString *bundleRoot = [[NSBundle bundleWithPath:docsPath] bundlePath];
//then get its content
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bundleRoot error:nil];
// this counts the total of jpg images contained in the local document folder of the app
NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.JPG'"]];
// in console tell me how many jpg do I have
NSLog(@"numero de fotos en total: %i", [onlyJPGs count]);
// ---------------

если вы хотите узнать, что находится в папке с документами (ту, которую вы можете просмотреть в iOS Simulator

через ~ / YourUserName / Библиотека / Поддержка приложений / iPhone Simulator / versioOfSimulator / Применение / appFolder / Документы)

вы бы использовали NSString *bundleRoot = [[NSBundle mainBundle] bundlePath]; вместо.

Надеюсь, это поможет тебе, приятель!

1 голос
/ 24 февраля 2011

Я не совсем уверен, к чему вы клоните, но общий подход к использованию файла из пакета вашего приложения состоит в том, чтобы скопировать его в каталог документов следующим образом:

  1. Проверьте (при первом запуске, запуске или при необходимости) наличие файла в каталоге документов.

  2. Если его нет, скопируйте версию "install"файл из вашего пакета в каталог документов.

С точки зрения некоторого примера кода, я использую метод для следующих целей:

- (BOOL)copyFromBundle:(NSString *)fileName {

    BOOL copySucceeded = NO;

    // Get our document path.
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [searchPaths objectAtIndex:0];

    // Get the full path to our file.
    NSString *filePath = [documentPath stringByAppendingPathComponent:fileName];

    NSLog(@"copyFromBundle - checking for presence of \"%@\"...", fileName);

    // Get a file manager
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Does the database already exist? (If not, copy it from our bundle)
    if(![fileManager fileExistsAtPath:filePath]) {

        // Get the bundle location
        NSString *bundleDBPath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];

        // Copy the DB to our document directory.
        copySucceeded = [fileManager copyItemAtPath:bundleDBPath
                                             toPath:filePath
                                              error:nil];

        if(!copySucceeded) {
            NSLog(@"copyFromBundle - Unable to copy \"%@\" to document directory.", fileName);
        }
        else {
            NSLog(@"copyFromBundle - Succesfully copied \"%@\" to document directory.", fileName);
        }

    }
    else {
        NSLog(@"copyFromBundle - \"%@\" already exists in document directory - ignoring.", fileName);   
    }

    return copySucceeded;
}

Это проверит наличие именованного файла в вашем каталоге документов и скопирует файл из вашего пакета, если он еще не существует.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...