Get List Of Specified File Types (png, xml, etc) In Any Folder
June 18, 2012
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.



