[swift] Swift에서 디렉토리 삭제와 관련된 날짜 제한 설정하기

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

디렉토리 삭제

먼저, 특정 디렉토리의 모든 파일을 삭제하는 방법에 대해 알아봅시다. 아래는 Swift에서 디렉토리를 지우기 위한 코드입니다.

import Foundation

func deleteFilesInDirectory(atPath path: String) {
    let fileManager = FileManager.default
    do {
        let filePaths = try fileManager.contentsOfDirectory(atPath: path)
        for filePath in filePaths {
            try fileManager.removeItem(atPath: "\(path)/\(filePath)")
        }
    } catch {
        print("Error: \(error)")
    }
}

위의 코드에서 deleteFilesInDirectory 함수는 해당 경로의 디렉토리 안에 있는 모든 파일을 삭제합니다.

날짜 제한 설정

이제, 특정 날짜 이전의 파일만 삭제하도록 조건을 추가해보겠습니다. 다음은 이를 수행하는 방법입니다.

func deleteFilesBeforeDate(inDirectory directoryPath: String, beforeDate date: Date) {
    let fileManager = FileManager.default
    do {
        let filePaths = try fileManager.contentsOfDirectory(atPath: directoryPath)
        for filePath in filePaths {
            let fullFilePath = directoryPath.appending("/").appending(filePath)
            if let fileAttributes = try? fileManager.attributesOfItem(atPath: fullFilePath),
                let modificationDate = fileAttributes[.modificationDate] as? Date {
                if modificationDate < date {
                    try fileManager.removeItem(atPath: fullFilePath)
                }
            }
        }
    } catch {
        print("Error: \(error)")
    }
}

위의 코드에서 deleteFilesBeforeDate 함수는 해당 경로의 디렉토리 안에 있는 파일 중, 특정 날짜 이전에 수정된 파일만 삭제합니다.

이제, 이러한 기능을 이용하여 Swift에서 디렉토리의 파일을 삭제하고, 특정 날짜 이전의 파일을 삭제하는 방법에 대해 알아보았습니다.

이 글이 도움이 되었기를 바랍니다. 감사합니다!

참고 자료