Create a folder inside documents folder in iOS apps

后端 未结 9 1000
一生所求
一生所求 2020-11-28 17:51

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!

相关标签:
9条回答
  • 2020-11-28 18:17

    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");
    }
    
    0 讨论(0)
  • 2020-11-28 18:28

    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...")
        }
    
    }
    
    0 讨论(0)
  • 2020-11-28 18:30

    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)")
                    }
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题