web-dev-qa-db-fra.com

Comment créer un répertoire en utilisant Swift (NSFileManager)

La conversion du code Objective-C pour créer un répertoire pour Swift pose quelques problèmes.

Objectif c:

    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];
42
Gian

Swift 5.

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let docURL = URL(string: documentsDirectory)!
let dataPath = docURL.appendingPathComponent("MyFolder")
if !FileManager.default.fileExists(atPath: dataPath.absoluteString) {
    do {
        try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: true, attributes: nil)
    } catch {
        print(error.localizedDescription);
    }
}

Swift 4.

let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentsDirectory: AnyObject = paths[0] as AnyObject
let dataPath = documentsDirectory.appendingPathComponent("MyFolder")!

do {
    try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
    print(error.localizedDescription);
}

Swift 3.

let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
let dataPath = documentsDirectory.appendingPathComponent("MyFolder")!

do {
    try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
    print(error.localizedDescription);
}

Swift 2.1

Vous pouvez créer un répertoire en utilisant la méthode ci-dessous:

let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
let dataPath = documentsDirectory.stringByAppendingPathComponent("MyFolder")

do {
    try NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
    print(error.localizedDescription);
}
92
Kampai

Aucune des réponses de @Kampai et @ Crashalot n'a fonctionné pour moi.

Le . AbsoluteString crée une URL avec le préfixe file: // et provoque une exception lors de la création du répertoire. Au lieu de cela, j'ai utilisé la méthode . Path.

Le code fixe pour Swift

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let dataPath = documentsDirectory.appendingPathComponent("MyFolder")

do {
    try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
    print("Error creating directory: \(error.localizedDescription)")
}
60
Mehdi Hosseinzadeh

La réponse acceptée ne se compile plus car la ligne avec appendingPathComponent génère une erreur.

Voici une version Swift 3 qui compile:

fileprivate func createDir(dirName: String) {
    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let dataPath = documentsDirectory.appendingPathComponent(dirName)

    do {
        try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
    } catch let error as NSError {
        printError("Error creating directory: \(error.localizedDescription)")
    }
}
5
Crashalot

Swift 4:

NSSearchPathForDirectoriesInDomains renvoie un tableau de chaînes, pas d'URL.

appendingPathComponent à string provoque le blocage de l'application avec le message - [NSPathStore2 URLByAppendingPathComponent:]: sélecteur non reconnu envoyé à l'instance

Voici une version Swift 4 qui compile:

    let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    if let pathURL = URL.init(string: paths[0]) {
        let dataURL = pathURL.appendingPathComponent("MyFolder")
        do {
            try FileManager.default.createDirectory(atPath: dataURL.absoluteString, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription);
        }
    }
    else {
        print("Error in getting path URL");
    }
3
Dhasdhageerkhan

Swift 4

// DB Directory and Path
lazy var applicationDocumentsDirectory: URL = {

    let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentDirectoryURL = urls[urls.count - 1] as URL
    let dbDirectoryURL = documentDirectoryURL.appendingPathComponent("DB")

    if FileManager.default.fileExists(atPath: dbDirectoryURL.path) == false{
        do{
            try FileManager.default.createDirectory(at: dbDirectoryURL, withIntermediateDirectories: false, attributes: nil)
        }catch{
        }
    }
    return dbDirectoryURL
}()
1
GSK

Solution plus simple:

"~/Desktop/demo".expand.createDir()//Now you have a folder named demo on your desk

extension String{
    func createDir(_ path:String){
        do {
            try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog("Unable to create directory \(error.debugDescription)")
        }
    }
    var expand:String {return NSString(string: self).expandingTildeInPath}
}
0
eonist

Pour les autres développeurs, je vais laisser cela ici, car cela pourrait aider quelqu'un comme moi à trouver un moyen de savoir où le dossier est créé.

let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDir = paths.firstObject as String
println("Path to the Documents directory\n\(documentsDir)")
0
bona912