nc14
nc14

Reputation: 559

Naming of folder in documents directory Swift

I'm using the following code (lifted from another answer) to create a folder in the documents directory (my app requires an export of a file). I'm trying to name this folder but the folder is creating with the name of the Xcode project rather than the name I have specified :

func createFileDirectory() {
    let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])

//set the name of the new folder
    let folderPath = documentsPath.appendingPathComponent("MY NAME HERE")
    do
    {
        try FileManager.default.createDirectory(atPath: folderPath!.path, withIntermediateDirectories: true, attributes: nil)
    }
    catch let error as NSError
    {
        NSLog("Unable to create directory \(error.debugDescription)")
    }
}

So when the user is able to save to files, it should allow them to save to a folder called "MY FOLDER HERE" but it just creates a folder with the name of the Xcode project ("MY_PROJECT")

I can't find any other answers other than the one that gave me the answer in the first place here

I can't see where I'm doing anything wrong? It's creating a folder it's just ignoring the name?

UPDATE

Following answers I've updated to the URL API method and removed spaces from the target folder name but still getting the wrong folder name (of the project name)

updated code:

func createFileDirectory() {
    let documentsURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)

    //set the name of the new folder
    let folderURL = documentsURL.appendingPathComponent("FirstDraft")
    do
    {
        try FileManager.default.createDirectory(at: folderURL, withIntermediateDirectories: true)
    }
    catch let error as NSError
    {
        NSLog("Unable to create directory \(error.debugDescription)")
    }
}

Upvotes: 1

Views: 2741

Answers (1)

vadian
vadian

Reputation: 285240

Please use the URL related API. It's much more reliable

func createFileDirectory() {
    let documentsURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)

    //set the name of the new folder
    let folderURL = documentsURL.appendingPathComponent("MY NAME HERE")
    do
    {
        try FileManager.default.createDirectory(at: folderURL, withIntermediateDirectories: true)
    }
    catch let error as NSError
    {
        NSLog("Unable to create directory \(error.debugDescription)")
    }
}

Upvotes: 4

Related Questions