Get List Of Specified File Types (png, xml, etc) In Any Folder

This tip shows how to get a list of file types using the NSPredicate object.

For example, let’s say you need a list of all the PNG files included in your application bundle:

NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
 
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *bundleDirectory = [fileManager contentsOfDirectoryAtPath:bundlePath error:nil];
 
NSPredicate *filter = [NSPredicate predicateWithFormat:@"self ENDSWITH '.png'"];
NSArray *pngFiles = [bundleDirectory filteredArrayUsingPredicate:filter];
 
NSLog(@"PNG files: %@", pngFiles);

Here is the output:


PNG files: (
“logo.png”,
“photo.png”,
“test.png”,
“testImage.png”
)

Here is another example using the Documents directory:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 
if ([paths count] > 0)
{
  NSFileManager *fileManager = [NSFileManager defaultManager];
  NSArray *directoryContents = [fileManager contentsOfDirectoryAtPath:[paths objectAtIndex:0] error:nil];
 
  if ([directoryContents count] > 0)
  {
    NSPredicate *filter = [NSPredicate predicateWithFormat:@"self ENDSWITH '.png'"];
    NSArray *pngFiles = [directoryContents filteredArrayUsingPredicate:filter];
 
    NSLog(@"PNG files: %@", pngFiles);
  }
}

You can change the path and filter as needed to list files of any type, in any folder.

  1. Hi,

    there is a one-liner to accomplish that:

    NSArray *filesURLs = [[NSBundle mainBundle] URLsForResourcesWithExtension:@”png” subdirectory:nil];

    • Thank you for pointing that out. I’ll update the example to use the Documents directory, which will make this example a little more relevant.

  2. Definitely a good trick, thanks for sharing.

Comments are closed.