Create a folder inside documents folder in iOS apps

110,512

Solution 1

I do that the following way:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

Solution 2

I don't have enough reputation to comment on Manni's answer, but [paths objectAtIndex:0] is the standard way of getting the application's Documents Directory

http://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/StandardBehaviors/StandardBehaviors.html#//apple_ref/doc/uid/TP40007072-CH4-SW6

Because the NSSearchPathForDirectoriesInDomains function was designed originally for Mac OS X, where there could be more than one of each of these directories, it returns an array of paths rather than a single path. In iOS, the resulting array should contain the single path to the directory. Listing 3-1 shows a typical use of this function.

Listing 3-1 Getting the path to the application’s Documents directory

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

Solution 3

Swift 3 Solution:

private func createImagesFolder() {
        // path to documents directory
        let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        if let documentDirectoryPath = documentDirectoryPath {
            // create the custom folder path
            let imagesDirectoryPath = documentDirectoryPath.appending("/images")
            let fileManager = FileManager.default
            if !fileManager.fileExists(atPath: imagesDirectoryPath) {
                do {
                    try fileManager.createDirectory(atPath: imagesDirectoryPath,
                                                    withIntermediateDirectories: false,
                                                    attributes: nil)
                } catch {
                    print("Error creating images folder in documents dir: \(error)")
                }
            }
        }
    }

Solution 4

I don't like "[paths objectAtIndex:0]" because if Apple adds a new folder starting with "A", "B" oder "C", the "Documents"-folder isn't the first folder in the directory.

Better:

NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

Solution 5

The Swift 2 solution:

let documentDirectoryPath: String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
if !NSFileManager.defaultManager().fileExistsAtPath(documentDirectoryPath) {
        do {
            try NSFileManager.defaultManager().createDirectoryAtPath(documentDirectoryPath, withIntermediateDirectories: false, attributes: nil)

        } catch let createDirectoryError as NSError {
            print("Error with creating directory at path: \(createDirectoryError.localizedDescription)")
        }

    }
Share:
110,512

Related videos on Youtube

Mina Mikhael
Author by

Mina Mikhael

10 years’ experience and a real passion for mobile application development. Readily embracing cutting-edge technology, I have gained an in-depth understanding of the main mobile platforms and recognize the subtle differences between each. Having helped develop a series of commercially successful apps on iOS.

Updated on February 18, 2020

Comments

  • Mina Mikhael
    Mina Mikhael about 4 years

    I just want to create new folders in the documents folder of my iPhone app.

    Does anybody know how to do that?

    Appreciate your help!

  • Mina Mikhael
    Mina Mikhael over 14 years
    thanks for the reply, it works but it creates the folder "MyFolder" beside the documents folder of the app .. not inside it. don't know why actually
  • Vladimir
    Vladimir over 14 years
    Sorry - was a typo there - must append @"/MyFolder", not @"MyFolder" to a documents path.
  • Andreas
    Andreas over 14 years
    You might want to change the third line to NSString *dataPath = [documentsDirectory stringByAppendingString:@"/MyFolder"]; since NSSearchPathForDirectoriesInDomains doesn't return trailing slashes.
  • SinisterMJ
    SinisterMJ over 14 years
    I fixed the code to use the more correct "stringByAppendingPathComponent", which does the right thing regardless of either input string having a "/" or not.
  • scubadivingfool
    scubadivingfool about 13 years
    See Tim's answer. Using NSSearchPathForDirectoryiesInDomains is the standard way of retrieving a users Documents directory.
  • Cathy
    Cathy over 12 years
    Helped me a lot.. Thanks Vladimir
  • Panos
    Panos over 11 years
    I am using this way to create a folder in documents folder. But it works fine in iphone 3gs with ios 5.0.1 , but on iphone 4 with ios 4.3.3 it fails to create the folder and the app then crashes. Any suggestions?
  • Panos
    Panos over 11 years
    @Vladimir I cannot see because I have installed the app without apple licence. It tries to create /User/Documents/MyAppName . On my 3gs with 5.0.1 it works fine. On iphone 4 with 4.3.3 it fails.
  • Panos
    Panos over 11 years
    using ls -l on both phones I see that the one that works has: -drwxrwxrwx 5 mobile mobile 238 Aug 13 18:12 Documents The one that does not: -drwxr-xr-x 3 root mobile 102 Aug 13 18:08 Documents How do I change it?
  • Vladimir
    Vladimir over 11 years
    @Panos, sorry dunno about jailbroken devices. Anyway, path you've mentioned is outside the application sandbox? May be that worth separate question
  • Panos
    Panos over 11 years
    @Vladimir Yes that path is outside the app sandbox. This is the Full path in the phones unix filesystem "/User/Documents/MyAppName". Maybe I won't have this problem when I get my Developers License and I install the app as it should :)
  • S1LENT WARRIOR
    S1LENT WARRIOR almost 10 years
    I think the simplest way to retrieve the documents directory path is: NSString* path = [@"~/Documents" stringByExpandingTildeInPath];
  • Mehlyfication
    Mehlyfication over 9 years
    If Apple decides to rename the Documents directory to "MyDocuments" (or similar), your approach won't work either.
  • ParkerHalo
    ParkerHalo about 8 years
    6.5 years later and it still works like a charm! thanks a lot, you saved my day!
  • Pradeep Reddy Kypa
    Pradeep Reddy Kypa over 6 years
    It should be NSDocumentDirectory instead of NSDocumentsDirectory
  • Logger
    Logger over 5 years
    how to write data into newly created directory?