3

I have functions to create directorys:

func createSystemFolders(){
        // Create a FileManager instance
        let fileManager = FileManager.default
        do {
            try fileManager.createDirectory(atPath: "json", withIntermediateDirectories: true, attributes: nil)
        }
        catch let error as NSError {
            debugPrint("\(ErrorsLabels.AppDelegate01): \(error)")
        }

        do {
            try fileManager.createDirectory(atPath: "inspirations", withIntermediateDirectories: true, attributes: nil)
        }
        catch let error as NSError {
            debugPrint("\(ErrorsLabels.AppDelegate02): \(error)")
        }

        do {
            try fileManager.createDirectory(atPath: "products", withIntermediateDirectories: true, attributes: nil)
        }
        catch let error as NSError {
            debugPrint("\(ErrorsLabels.AppDelegate03): \(error)")
        }
    }

I need second function to check directory exist.

Haw can I check it?

Łukasz Betta
  • 131
  • 3
  • 12
  • Already answered https://stackoverflow.com/a/24696209/2463616 – pacification May 18 '18 at 07:27
  • 1
    Possible duplicate of [NSFileManager fileExistsAtPath:isDirectory and swift](https://stackoverflow.com/questions/24696044/nsfilemanager-fileexistsatpathisdirectory-and-swift) – dandan78 May 18 '18 at 08:08

4 Answers4

10

You can use this,

fileprivate func directoryExistsAtPath(_ path: String) -> Bool {
    var isdirectory : ObjCBool = true
    let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
    return exists && isDirectory.boolValue
}
PPL
  • 6,357
  • 1
  • 11
  • 30
3

You can do smarter solution Like that without Two function completion(isExit,directoryURL) :

And simple use it in one line :

 self.createSystemFolders("json") { (isExit, url) in
                print(isExit)
                print(url)
            }

CreateSystemFolders:

 func createSystemFolders(_ folderName:String ,_ completion:(_ isExit:Bool?,_ directoryURL:URL?) -> Void){
    let paths = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true)
    let directory = paths[0]
    let fileManager = FileManager.default

    let url = URL(fileURLWithPath: directory).appendingPathComponent(folderName)


    if !fileManager.fileExists(atPath: url.path) {
        do {
            try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
            completion(false,url)
        }
        catch {
            print("Error: Unable to create directory: \(error)")
            completion(nil,nil)
        }
        var url = URL(fileURLWithPath: directory)
        var values = URLResourceValues()
        values.isExcludedFromBackup = true
        do {
            try url.setResourceValues(values)
            completion(false,url)
        }
        catch {
            print("Error: Unable to exclude directory from backup: \(error)")
            completion(nil,nil)
        }
    }else{
        completion(true,url)
    }
}
Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35
2

Try this:

let fileManager = FileManager.default
var isdirectory = true
if fileManager.fileExists(atPath: fullPath, isDirectory:&isdirectory) {
    if isdirectory.boolValue {
        // file exists and is a directory
    } else {
        // file exists and is not a directory
    }
} else {
    // file does not exist
}
iParesh
  • 2,338
  • 1
  • 18
  • 30
  • Here is link for more info https://developer.apple.com/documentation/foundation/filemanager/1410277-fileexists# – iParesh May 18 '18 at 07:29
0

here how you can

1 Find a Documents directory on device

2 Check if file exists at specified file path

let fileNameToDelete = "myFileName.txt"
        var filePath = ""        
        // Fine documents directory on device
         let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)

        if dirs.count > 0 {
            let dir = dirs[0] //documents directory
            filePath = dir.appendingFormat("/" + fileNameToDelete)
            print("Local path = \(filePath)")
        } else {
            print("Could not find local directory to store file")
            return
        }


        let fileManager = FileManager.default

        // Check if file exists
        if fileManager.fileExists(atPath: filePath) {
            print("File exists")
        } else {
            print("File does not exist")
        }
ArunPratap
  • 4,816
  • 7
  • 25
  • 43