[swift] Swift에서 특정 날짜 이전의 파일을 가진 디렉토리 삭제하기

Swift를 사용하여 디렉토리 내의 특정 날짜 이전의 파일을 삭제하는 방법에 대해 알아보겠습니다.

1. 특정 날짜 이전의 파일 확인하기

import Foundation

func deleteFilesOlderThanDate(date: Date, atPath path: String) {
    let fileManager = FileManager.default
    if let directoryContents = try? fileManager.contentsOfDirectory(atPath: path) {
        for fileName in directoryContents {
            let fileURL = URL(fileURLWithPath: path).appendingPathComponent(fileName)
            if let modifiedDate = try? fileManager.attributesOfItem(atPath: fileURL.path)[.modificationDate] as? Date {
                if modifiedDate < date {
                    // 파일 삭제
                    try? fileManager.removeItem(at: fileURL)
                }
            }
        }
    }
}

let directoryPath = "/path/to/directory"
let date = Date(timeIntervalSinceNow: -604800) // 1주일 전
deleteFilesOlderThanDate(date: date, atPath: directoryPath)

2. 사용 예시

위의 예시 코드는 fileManager.contentsOfDirectory 메서드를 사용하여 디렉토리 내의 파일 목록을 가져온 뒤, 각 파일의 수정 날짜를 확인하고 특정 날짜 이전의 파일을 삭제하는 함수를 구현한 것입니다.

이제 원하는 디렉토리의 경로와 삭제하고자 하는 날짜를 설정하여 사용하면 됩니다. 코드 실행 후 해당 디렉토리에는 설정한 날짜 이전의 파일들이 삭제될 것입니다.

위의 코드를 활용하여 디렉토리 내의 파일을 제거하는 기능을 구현할 수 있습니다.

참고 자료