ios objective-c swift nsfilemanager nsdocumentdirectory

ios - Cómo crear un directorio usando el código Swift(NSFileManager)



objective-c nsdocumentdirectory (7)

Tengo problemas para convertir el código Objective-C para crear un directorio para Swift.

C objetivo:

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


Solución más 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} }


La respuesta aceptada ya no se compila, ya que la línea con appendingPathComponent genera un error.

Aquí hay una versión de Swift 3 que compila:

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


Ninguna de las respuestas de @Kampai y @ Crashalot funcionó para mí.

The .absoluteString crea una url con el prefijo file: // y causa una excepción al crear el directorio. En cambio, he usado el método .path .

El código fijo para Swift 3

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


Para otros desarrolladores, voy a dejar esto aquí, ya que puede ayudar a alguien como yo a buscar una forma de averiguar dónde se está creando la carpeta.

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


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


Swift 4.0 editar

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

Editar Swift 3.0

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

Editar swift 2.1

Puede crear un directorio usando el siguiente método:

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


Swift 4:

NSSearchPathForDirectoriesInDomains devuelve una matriz de cadenas, no de URL.

anexarPathComponent a string hace que la aplicación se cuelgue con el mensaje - [NSPathStore2 URLByAppendingPathComponent:]: selector no reconocido enviado a la instancia

Aquí hay una versión de Swift 4 que compila:

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