Search code examples
iosnsfilemanager

Using NSFileManager to return if directory does not exit


I have the following code that returns an NSArray of the names of files in a given directory. This works fine when the directory exists but what I would like to know is how I can first check whether or not the directory at directoryPath actually exists.

NSString *directoryPath = [documentsDirectory stringByAppendingPathComponent:folderName];
NSArray *directoryContents = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:directoryPath error:nil];

Solution

  • The NSFileManager class has a built in method, which is used to check if a file exists at a path or not.

    The function goes like this :

    [fileManagerObject fileExistsAtPath : @"PUT_YOUR_FILE_PATH_HERE" isDirectory : YES]; //If its a file that you're looking to check then put isDirectory as NO, but if its a folder then enter YES as the parameter
    

    Here's how you would typically use it in your code :

    NSFileManager *fileManager = [[NSFileManager alloc] init];
    if([fileManager fileExistsAtPath:@"FILE_PATH_HERE" isDirectory:NO] == YES)
    {
       //Yes. The file exists, continue with your operation.
    }
    else
    {
       //No. The file doesn't exist.
    }