[swift] Swift에서 디렉토리 생성 후 권한 설정하기

Swift를 사용하여 디렉토리를 생성하고 권한을 설정하는 방법에 대해 알아보겠습니다.

디렉토리 생성

Swift에서 디렉토리를 생성하려면 FileManager를 사용해야 합니다. 아래는 createDirectory 메서드를 사용하여 디렉토리를 생성하는 예제 코드입니다.

import Foundation

let fileManager = FileManager.default
let directoryURL = URL(fileURLWithPath: "/path/to/directory")

do {
    try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
    print(error)
}

위 예제에서 /path/to/directory는 생성하려는 디렉토리의 경로를 나타냅니다.

권한 설정

디렉토리를 생성한 후에는 해당 디렉토리의 권한을 설정할 수 있습니다. 이를 위해 FileManagersetAttributes 메서드를 사용할 수 있습니다. 아래 예제 코드는 디렉토리의 권한을 설정하는 방법을 보여줍니다.

import Foundation

let fileManager = FileManager.default
let directoryURL = URL(fileURLWithPath: "/path/to/directory")
let attributes = [FileAttributeKey.posixPermissions: 0o755]

do {
    try fileManager.setAttributes(attributes, ofItemAtPath: directoryURL.path)
} catch {
    print(error)
}

위 예제에서 0o755는 소유자에 대한 읽기, 쓰기, 실행 권한 및 그룹 및 다른 사용자에 대한 읽기 및 실행 권한을 설정합니다.

이제 Swift를 사용하여 디렉토리를 생성하고 권한을 설정하는 방법을 알게 되었습니다.

참고 자료