Search code examples
iosswift

How check directory exist?


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?


Solution

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