151

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!

Lorenzo B
  • 33,006
  • 23
  • 110
  • 185
Mina Mikhael
  • 2,799
  • 6
  • 25
  • 31

9 Answers9

327

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
mryuso92
  • 207
  • 1
  • 19
Vladimir
  • 167,138
  • 35
  • 380
  • 310
  • 1
    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 – Mina Mikhael Nov 19 '09 at 12:22
  • 3
    Sorry - was a typo there - must append @"/MyFolder", not @"MyFolder" to a documents path. – Vladimir Nov 19 '09 at 12:26
  • 2
    You might want to change the third line to NSString *dataPath = [documentsDirectory stringByAppendingString:@"/MyFolder"]; since NSSearchPathForDirectoriesInDomains doesn't return trailing slashes. – Andreas Nov 19 '09 at 12:35
  • 14
    I fixed the code to use the more correct "stringByAppendingPathComponent", which does the right thing regardless of either input string having a "/" or not. – Kendall Helmstetter Gelner Nov 19 '09 at 15:48
  • Helped me a lot.. Thanks Vladimir – Cathy Dec 20 '11 at 09:21
  • 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 Aug 13 '12 at 15:16
  • @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 Aug 13 '12 at 15:23
  • 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? – Panos Aug 13 '12 at 15:32
  • @Panos, sorry dunno about jailbroken devices. Anyway, path you've mentioned is outside the application sandbox? May be that worth separate question – Vladimir Aug 13 '12 at 15:34
  • @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 :) – Panos Aug 13 '12 at 15:44
  • 6.5 years later and it still works like a charm! thanks a lot, you saved my day! – ParkerHalo Mar 29 '16 at 08:12
14

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)")
                }
            }
        }
    }
Miralem Cebic
  • 1,266
  • 1
  • 15
  • 28
14

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];
Tim
  • 343
  • 2
  • 7
  • 1
    I think the simplest way to retrieve the documents directory path is: `NSString* path = [@"~/Documents" stringByExpandingTildeInPath];` – S1LENT WARRIOR Jul 21 '14 at 12:15
9

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
Manni
  • 10,948
  • 15
  • 46
  • 67
  • 8
    See Tim's answer. Using NSSearchPathForDirectoryiesInDomains is the standard way of retrieving a users Documents directory. – Tim Swast Mar 18 '11 at 01:11
  • 1
    If Apple decides to rename the Documents directory to "MyDocuments" (or similar), your approach won't work either. – Mehlyfication Dec 05 '14 at 08:01
8

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)")
        }

    }
rafalkitta
  • 492
  • 6
  • 9
5

This works fine for me,

NSFileManager *fm = [NSFileManager defaultManager];
NSArray *appSupportDir = [fm URLsForDirectory:NSDocumentsDirectory inDomains:NSUserDomainMask];
NSURL* dirPath = [[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:@"YourFolderName"];

NSError*    theError = nil; //error setting
if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES
                           attributes:nil error:&theError])
{
   NSLog(@"not created");
}
Tong Liu
  • 71
  • 1
  • 3
4

Swift 4.0

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
// Get documents folder
let documentsDirectory: String = paths.first ?? ""
// Get your folder path
let dataPath = documentsDirectory + "/yourFolderName"
if !FileManager.default.fileExists(atPath: dataPath) {
    // Creates that folder if not exists
    try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
}
Abhishek Jain
  • 4,155
  • 2
  • 27
  • 29
1

Following code may help in creating directory :

-(void) createDirectory : (NSString *) dirName {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Fetch path for document directory
dataPath = (NSMutableString *)[documentsDirectory stringByAppendingPathComponent:dirName];

NSError *error;

if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]) {
    NSLog(@"Couldn't create directory error: %@", error);
}
else {
    NSLog(@"directory created!");
}

NSLog(@"dataPath : %@ ",dataPath); // Path of folder created

}

Usage :

[self createDirectory:@"MyFolder"];

Result :

directory created!

dataPath : /var/mobile/Applications/BD4B5566-1F11-4723-B54C-F1D0B23CBC/Documents/MyFolder

Jayprakash Dubey
  • 32,447
  • 16
  • 161
  • 169
1

Swift 1.2 and iOS 8

Create custom directory (name = "MyCustomData") inside the documents directory but only if the directory does not exist.

// path to documents directory
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String

// create the custom folder path
let myCustomDataDirectoryPath = documentDirectoryPath.stringByAppendingPathComponent("/MyCustomData")

// check if directory does not exist
if NSFileManager.defaultManager().fileExistsAtPath(myCustomDataDirectoryPath) == false {

    // create the directory
    var createDirectoryError: NSError? = nil
    NSFileManager.defaultManager().createDirectoryAtPath(myCustomDataDirectoryPath, withIntermediateDirectories: false, attributes: nil, error: &createDirectoryError)

    // handle the error, you may call an exception
    if createDirectoryError != nil {
        println("Handle directory creation error...")
    }

}
user3378170
  • 2,191
  • 19
  • 11