[swift] Swift에서 디렉토리 삭제 시 파일 삭제 로그 기록하기
이번에는 Swift에서 디렉토리를 삭제할 때 그 안에 있는 파일들의 삭제를 로그로 남기는 방법에 대해 알아보겠습니다. 이렇게 함으로써 파일이 삭제된 이력을 추적하고 디버깅하는 데에 도움이 됩니다.
1. 디렉토리 삭제 및 파일 삭제 로그 작성
다음은 Swift로 디렉토리를 삭제하고 해당 디렉토리 안에 있는 파일들의 삭제를 로그에 남기는 방법입니다.
import Foundation
func deleteDirectory(atPath path: String) throws {
let fileManager = FileManager.default
let url = URL(fileURLWithPath: path)
let fileURLs = try fileManager.contentsOfDirectory(at: url, includingPropertiesForKeys: nil)
try fileURLs.forEach { fileURL in
try fileManager.removeItem(at: fileURL)
// 파일 삭제 로그 작성
print("Deleted file at: \(fileURL.path)")
}
try fileManager.removeItem(at: url)
// 디렉토리 삭제 로그 작성
print("Deleted directory at: \(url.path)")
}
do {
try deleteDirectory(atPath: "path_to_directory")
} catch {
print(error)
}
위의 예시 코드에서는 deleteDirectory
메서드를 통해 디렉토리 안에 있는 파일들을 삭제하고 삭제된 파일들의 경로를 출력합니다. 마지막으로 디렉토리도 삭제하여 그 경로를 출력합니다.
2. 코드 설명
FileManager
클래스의contentsOfDirectory(at:includingPropertiesForKeys:)
메서드를 사용하여 디렉토리 안에 있는 파일들의 URL을 가져옵니다.forEach
를 사용하여 각 파일을 순회하면서removeItem(at:)
메서드를 사용하여 파일을 삭제하고 삭제된 파일 경로를 로그에 출력합니다.- 모든 파일이 삭제된 후에는
removeItem(at:)
메서드를 사용하여 디렉토리를 삭제하고 해당 경로를 로그에 출력합니다.
이제 Swift로 디렉토리를 삭제할 때에 파일 삭제 로그를 기록하는 방법을 알게 되었습니다. 이를 응용하여 실제 프로젝트에서 사용해보면 유용할 것입니다.
참조: Swift FileManager, Swift closures
#AI_목차
- 디렉토리 삭제 및 파일 삭제 로그 작성
- 코드 설명