O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.4. Enumerating Files and Folders

Problem

You either want to enumerate folders within a folder or you want to enumerate the list of files inside a folder. The act of enumerating means that you simply want to find all the folders and/or files within another folder.

Solution

Use the contentsOfDirectoryAtPath:error: instance method of the NSFileManager class as shown here. In this example, we are enumerating all the files, folders, and symlinks under our app’s bundle folder:

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSString *bundleDir = [[NSBundle mainBundle] bundlePath];
    
    NSError *error = nil;
    NSArray *bundleContents = [fileManager
                               contentsOfDirectoryAtPath:bundleDir
                               error:&error];
    
    if ([bundleContents count] > 0 &&
        error == nil){
        NSLog(@"Contents of the app bundle = %@", bundleContents);
    }
    else if ([bundleContents count] == 0 &&
             error == nil){
        NSLog(@"Call the police! The app bundle is empty.");
    }
    else {
        NSLog(@"An error happened = %@", error);
    }
    
    self.window = [[UIWindow alloc]
                   initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

Discussion

In some of your iOS apps, you may need to enumerate the contents of a folder. Let me give you an example, in case this need is a bit vague right now. Imagine that the user ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required