如何检查目录是否存在?

Łuk*_*tta 5 ios swift

我有创建目录的功能:

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)")
        }
    }
Run Code Online (Sandbox Code Playgroud)

我需要第二个函数来检查目录是否存在。

我怎样才能检查它?

PPL*_*PPL 11

你可以用这个,

fileprivate func directoryExistsAtPath(_ path: String) -> Bool {
    var isdirectory : ObjCBool = true
    let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
    return exists && isDirectory.boolValue
}
Run Code Online (Sandbox Code Playgroud)


Abd*_*ish 3

您可以做更智能的解决方案,就像没有两个功能一样 completion(isExit,directoryURL)

并简单地在一行中使用它

 self.createSystemFolders("json") { (isExit, url) in
                print(isExit)
                print(url)
            }
Run Code Online (Sandbox Code Playgroud)

创建系统文件夹:

 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)
    }
}
Run Code Online (Sandbox Code Playgroud)