Прочитать файл изображения из пользовательского каталога, используя NSBundle - PullRequest
0 голосов
/ 30 июня 2011

Создание пользовательского каталога со всеми изображениями.Разработка его на заказ, потому что это поможет мне получать изображения, когда мне это нужно, в разных местах конфигурации.

NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];       
[filemgr createDirectoryAtPath: @"/Users/home/lifemoveson/test" withIntermediateDirectories:YES attributes: nil error:NULL];

Я поместил изображения в тестовую папку и относился к типу .png.Есть ли способ получить изображения, как показано ниже.

/ ** снова ОБНОВЛЕНО ** /

В настоящее время эта папка находится в Application_Home / Resources / ImageTiles / согласно примеру Photoscroller.Как мы можем изменить его на / Users / home / lifemoveson / test / ImageTiles / folder?

- (UIImage *)tileForScale:(CGFloat)scale row:(int)row col:(int)col
{
// we use "imageWithContentsOfFile:" instead of "imageNamed:" here because we don't want UIImage to cache our tiles
NSString *tileName = [NSString stringWithFormat:@"%@_%d_%d_%d", imageName, (int)(scale * 1000), col, row];

// Currently this folder is under <Application_Home>/Resources/ImageTiles/ as per Photoscroller example. 
// How can we change it to /Users/home/lifemoveson/test/ImageTiles/ folder ?
NSString *path = [[NSBundle mainBundle] pathForResource:tileName ofType:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];
return image;
}

Ответы [ 2 ]

0 голосов
/ 30 июня 2011

Макин вызов функций, таких как

NSString* newDirPath = [self createDirectoryWithName:@"Test"];
if (newDirPath) {
    [self saveFile:@"MasterDB.sqlite" atPath:newDirPath];
}

которые реализованы следующим образом

-(NSString*)createDirectoryWithName:(NSString*)dirName{

    NSArray* directoryArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask , YES);
    NSString* directoryPath = [directoryArray objectAtIndex:0];
    NSString* newPath = [directoryPath stringByAppendingString:[NSString stringWithFormat:@"/%@",dirName]];
    NSFileManager *filemamager = [NSFileManager defaultManager];       
    BOOL flag = [filemamager createDirectoryAtPath:newPath withIntermediateDirectories:YES attributes: nil error:NULL];
    return flag == YES ?newPath: nil;
}

-(BOOL)saveFile:(NSString*)fileName atPath:(NSString*)path{

    BOOL success;

    // Create a FileManager object, we will use this to check the status
    // of the File and to copy it over if required
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Check if the File has already been created in the users filesystem
    NSString *filePath = [path stringByAppendingPathComponent:fileName];

    success = [fileManager fileExistsAtPath:filePath];

    // If the File already exists then return without doing anything
    if(success) return YES;

    // If not then proceed to copy the File from the application to the users filesystem

    // Get the path to the database in the application package
    NSString *pathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];

    // Copy the database from the package to the users filesystem

    NSError *error = nil;

    BOOL flag = [fileManager copyItemAtPath:pathFromApp toPath:filePath error:&error];

    return flag;
}

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

0 голосов
/ 30 июня 2011

Приложения, работающие на iOS, помещаются в «песочницу»; Вы не можете просто создавать каталоги, где хотите. Ваш createDirectoryAtPath: вызов не удастся. Вместо этого вы должны использовать один из каталогов, выделенных для вашего приложения .

Как только вы получите путь для одного из этих каталогов, получение пути для файлов в них - это просто случай использования NSString stringByAppendingPathComponent: метода.

...