NSFileManager fileExistsAtPath:isDirectory and swift

后端 未结 4 1908
悲哀的现实
悲哀的现实 2020-11-30 04:44

I\'m trying to understand how to use the function fileExistsAtPath:isDirectory: with Swift but I get completely lost.

This is my code example:

相关标签:
4条回答
  • 2020-11-30 04:49

    Just to overload the bases. Here is mine that takes a URL

    extension FileManager {
    
        func directoryExists(atUrl url: URL) -> Bool {
            var isDirectory: ObjCBool = false
            let exists = self.fileExists(atPath: url.path, isDirectory:&isDirectory)
            return exists && isDirectory.boolValue
        }
    }
    
    0 讨论(0)
  • 2020-11-30 04:52

    I've just added a simple extension to FileManager to make this a bit neater. Might be helpful?

    extension FileManager {
    
        func directoryExists(_ atPath: String) -> Bool {
            var isDirectory: ObjCBool = false
            let exists = FileManager.default.fileExists(atPath: atPath, isDirectory:&isDirectory)
            return exists && isDirectory.boolValue
        }
    }
    
    0 讨论(0)
  • 2020-11-30 04:53

    The second parameter has the type UnsafeMutablePointer<ObjCBool>, which means that you have to pass the address of an ObjCBool variable. Example:

    var isDir : ObjCBool = false
    if fileManager.fileExistsAtPath(fullPath, isDirectory:&isDir) {
        if isDir {
            // file exists and is a directory
        } else {
            // file exists and is not a directory
        }
    } else {
        // file does not exist
    }
    

    Update for Swift 3 and Swift 4:

    let fileManager = FileManager.default
    var isDir : ObjCBool = false
    if fileManager.fileExists(atPath: fullPath, isDirectory:&isDir) {
        if isDir.boolValue {
            // file exists and is a directory
        } else {
            // file exists and is not a directory
        }
    } else {
        // file does not exist
    }
    
    0 讨论(0)
  • 2020-11-30 05:02

    Tried to improve the other answer to make it easier to use.

    enum Filestatus {
            case isFile
            case isDir
            case isNot
    }
    extension URL {
        
        
        var filestatus: Filestatus {
            get {
                let filestatus: Filestatus
                var isDir: ObjCBool = false
                if FileManager.default.fileExists(atPath: self.path, isDirectory: &isDir) {
                    if isDir.boolValue {
                        // file exists and is a directory
                        filestatus = .isDir
                    }
                    else {
                        // file exists and is not a directory
                        filestatus = .isFile
                    }
                }
                else {
                    // file does not exist
                    filestatus = .isNot
                }
                return filestatus
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题