Development Tip

NSFileManager fileExistsAtPath : isDirectory 및 swift

yourdevel 2020. 11. 19. 22:07
반응형

NSFileManager fileExistsAtPath : isDirectory 및 swift


fileExistsAtPath:isDirectory:Swift로 함수를 사용하는 방법을 이해하려고하는데 완전히 길을 잃었습니다.

이것은 내 코드 예제입니다.

var b:CMutablePointer<ObjCBool>?

if (fileManager.fileExistsAtPath(fullPath, isDirectory:b! )){
    // how can I use the "b" variable?!
    fileManager.createDirectoryAtURL(dirURL, withIntermediateDirectories: false, attributes: nil, error: nil)
}

bMutablePointer 의 값에 어떻게 액세스 할 수 있는지 이해할 수 없습니다 . YES또는로 설정되어 있는지 알고 싶으면 어떻게 NO합니까?


번째 매개 변수 의 유형 변수 UnsafeMutablePointer<ObjCBool>주소 를 전달해야 함을 의미 ObjCBool합니다. 예:

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
}

Swift 3 및 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
}

사용하기 쉽도록 다른 답변을 개선하려고했습니다.

extension URL {
    enum Filestatus {
        case isFile
        case isDir
        case isNot
    }

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

참고 URL : https://stackoverflow.com/questions/24696044/nsfilemanager-fileexistsatpathisdirectory-and-swift

반응형