[swift] Swift에서 파일의 생성 시간 확인하는 방법

Swift 언어를 사용하여 파일의 생성 시간을 확인하는 방법을 알아보겠습니다.

1. 파일의 경로 설정하기

먼저, 생성 시간을 확인하고자 하는 파일의 경로를 지정해야 합니다. 이를 위해서는 URL 객체를 사용합니다. 예를 들어, 현재 작업 디렉토리에 있는 example.txt 파일의 경로를 다음과 같이 설정합니다.

경로 설정 방법:

let fileURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("example.txt")

2. 파일의 속성 가져오기

파일의 속성을 가져오기 위해서는 FileManager.default 객체의 attributesOfItem 메서드를 사용합니다. 이 메서드는 파일의 경로를 매개변수로 받아 해당 파일의 속성을 NSDictionary 타입으로 리턴합니다. 따라서, attributesOfItem 메서드를 사용하여 파일의 생성 시간을 가져올 수 있습니다. 다음은 파일의 속성을 가져와서 생성 시간을 출력하는 예제 코드입니다.

예제 코드:

do {
    let fileAttributes = try FileManager.default.attributesOfItem(atPath: fileURL.path)
    if let creationDate = fileAttributes[FileAttributeKey.creationDate] as? Date {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let formattedCreationDate = dateFormatter.string(from: creationDate)
        print("파일의 생성 시간: \(formattedCreationDate)")
    }
} catch {
    print("파일 속성을 가져오는 데 실패했습니다.")
}

위 코드에서는 FileAttributeKey.creationDate 키를 사용하여 파일의 생성 시간을 가져오고, DateFormatter를 사용하여 날짜를 원하는 형식으로 포맷팅합니다. 마지막으로, 포맷팅된 생성 시간을 출력합니다.

참고 자료