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

Получение списка файлов в папке "Ресурсы" - iOS

Скажем, у меня есть папка в моей папке "Ресурсы" моего приложения iPhone под названием "Документы".

Есть ли способ, которым я могу получить массив или некоторый тип списка всех файлов, включенных в эту папку во время выполнения?

Итак, в коде это выглядело бы так:

NSMutableArray *myFiles = [...get a list of files in Resources/Documents...];

Возможно ли это?

4b9b3361

Ответ 1

Вы можете получить путь к каталогу Resources, подобному этому,

NSString * resourcePath = [[NSBundle mainBundle] resourcePath];

Затем добавьте Documents к пути,

NSString * documentsPath = [resourcePath stringByAppendingPathComponent:@"Documents"];

Затем вы можете использовать любые API-интерфейсы списков каталогов NSFileManager.

NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];

Примечание. При добавлении исходной папки в комплект убедитесь, что вы выбрали "Создать ссылки на папки для любых добавленных папок при копировании"

Ответ 2

Вы также можете попробовать этот код:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError * error;
NSArray * directoryContents =  [[NSFileManager defaultManager]
                      contentsOfDirectoryAtPath:documentsDirectory error:&error];

NSLog(@"directoryContents ====== %@",directoryContents);

Ответ 3

Swift

Обновлен для Swift 3

let docsPath = Bundle.main.resourcePath! + "/Resources"
let fileManager = FileManager.default

do {
    let docsArray = try fileManager.contentsOfDirectory(atPath: docsPath)
} catch {
    print(error)
}

Дальнейшее чтение:

Ответ 4

Быстрая версия:

    if let files = try? FileManager.default.contentsOfDirectory(atPath: Bundle.main.bundlePath ){
        for file in files {
            print(file)
        }
    }

Ответ 5

Список всех файлов в каталоге

     NSFileManager *fileManager = [NSFileManager defaultManager];
     NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
     NSArray *contents = [fileManager contentsOfDirectoryAtURL:bundleURL
                           includingPropertiesForKeys:@[]
                                              options:NSDirectoryEnumerationSkipsHiddenFiles
                                                error:nil];

     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pathExtension ENDSWITH '.png'"];
     for (NSString *path in [contents filteredArrayUsingPredicate:predicate]) {
        // Enumerate each .png file in directory
     }

Рекурсивно перечислить файлы в каталоге

      NSFileManager *fileManager = [NSFileManager defaultManager];
      NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
      NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:bundleURL
                                   includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey]
                                                     options:NSDirectoryEnumerationSkipsHiddenFiles
                                                errorHandler:^BOOL(NSURL *url, NSError *error)
      {
         NSLog(@"[Error] %@ (%@)", error, url);
      }];

      NSMutableArray *mutableFileURLs = [NSMutableArray array];
      for (NSURL *fileURL in enumerator) {
      NSString *filename;
      [fileURL getResourceValue:&filename forKey:NSURLNameKey error:nil];

      NSNumber *isDirectory;
      [fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];

       // Skip directories with '_' prefix, for example
      if ([filename hasPrefix:@"_"] && [isDirectory boolValue]) {
         [enumerator skipDescendants];
         continue;
       }

      if (![isDirectory boolValue]) {
          [mutableFileURLs addObject:fileURL];
       }
     }

Подробнее о NSFileManager здесь

Ответ 6

Swift 3 (и возвращающие URL-адреса)

let url = Bundle.main.resourceURL!
    do {
        let urls = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys:[], options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
    } catch {
        print(error)
    }