31
votes

I am a new student in 9th grade learning swift, creating a school project .

I am trying to create a directory where I want to save a scanned file into pdf format.

While creating directory I am getting error below.

Error 1:

Cannot use instance member 'filemgr' within property initializer; property initializers run before 'self' is available.

Error 2:

Expected declaration

Code:

let filemgr = FileManager.default


let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask)

let docsURL = dirPaths[0]

let newDir = docsURL.appendingPathComponent("data").path

do{
    try filemgr.createDirectory(atPath: newDir,withIntermediateDirectories: true, attributes: nil)
} catch {
    print("Error: \(error.localizedDescription)")
}

Please assist me in resolving this issue.

Thanks.

5

5 Answers

50
votes

Please use this code:

Swift 5.0, Swift 4.0 And Swift 3.0

let DocumentDirectory = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
let DirPath = DocumentDirectory.appendingPathComponent("FOLDER_NAME")
do
{
    try FileManager.default.createDirectory(atPath: DirPath!.path, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError
{
    print("Unable to create directory \(error.debugDescription)")
}
print("Dir Path = \(DirPath!)")
45
votes

For Swift 4.0 Please use this

    let fileManager = FileManager.default
    if let tDocumentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
        let filePath =  tDocumentDirectory.appendingPathComponent("\(FOLDER_NAME)") 
        if !fileManager.fileExists(atPath: filePath.path) {
            do {
                try fileManager.createDirectory(atPath: filePath.path, withIntermediateDirectories: true, attributes: nil)
            } catch {
                NSLog("Couldn't create document directory")
            }
        }
        NSLog("Document directory is \(filePath)")
    }
23
votes

For Swift 4.0, I created the following extension off of URL that allows for the creation of a folder off of the documents directory within the application.

import Foundation

extension URL {
    static func createFolder(folderName: String) -> URL? {
        let fileManager = FileManager.default
        // Get document directory for device, this should succeed
        if let documentDirectory = fileManager.urls(for: .documentDirectory,
                                                    in: .userDomainMask).first {
            // Construct a URL with desired folder name
            let folderURL = documentDirectory.appendingPathComponent(folderName)
            // If folder URL does not exist, create it
            if !fileManager.fileExists(atPath: folderURL.path) {
                do {
                    // Attempt to create folder
                    try fileManager.createDirectory(atPath: folderURL.path,
                                                    withIntermediateDirectories: true,
                                                    attributes: nil)
                } catch {
                    // Creation failed. Print error & return nil
                    print(error.localizedDescription)
                    return nil
                }
            }
            // Folder either exists, or was created. Return URL
            return folderURL
        }
        // Will only be called if document directory not found
        return nil
    }
}

If the desired folder does not exist, it will create it. Then, assuming the folder exists, it returns the URL back to the user. Otherwise, if it fails, then nil is returned.

For example, to create the folder "MyStuff", you would call it like this:

let myStuffURL = URL.createFolder(folderName: "MyStuff")

This would return:

file:///var/mobile/Containers/Data/Application/4DE0A1C0-8629-47C9-87D7-C2B4F3A16D24/Documents/MyStuff/

You can also create nested folders with the following:

let myStuffHereURL = URL.createFolder(folderName: "My/Stuff/Here")

Which gives you:

file:///var/mobile/Containers/Data/Application/4DE0A1C0-8629-47C9-87D7-C2B4F3A16D24/Documents/My/Stuff/Here/

1
votes

You are getting this because you are assigning value to newDir instance at wrong place.

I wrote your code in viewDidLoad and it works perfectly.

enter image description here

0
votes

For Swift 5 and up Version

let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let directoryURL = documentDirectoryURL.appendingPathComponent("FolderName", isDirectory: true)
        
        if FileManager.default.fileExists(atPath: directoryURL.path) {
             print(directoryURL.path)
        } else {
            do {
                try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
                print(directoryURL.path)
            } catch {
                print(error.localizedDescription)
            }