[swift] Swift에서 디렉토리 삭제 시 파일 복사 후 원본 삭제 로그 기록하기

이번 블로그에서는 Swift 언어를 사용하여 디렉토리 삭제 시 파일을 복사하고 원본 삭제를 로그에 기록하는 방법에 대해 알아보겠습니다.

디렉토리 삭제 시 파일 복사하기

아래는 디렉토리를 삭제하기 전에 해당 디렉토리 안의 파일들을 다른 위치로 복사하는 Swift 코드 예제입니다.

import Foundation

func copyFilesBeforeDeletingDirectory(from sourceDirectory: URL, to destinationDirectory: URL) {
    let fileManager = FileManager.default
    do {
        let fileURLs = try fileManager.contentsOfDirectory(at: sourceDirectory, includingPropertiesForKeys: nil)
        for url in fileURLs {
            let destinationURL = destinationDirectory.appendingPathComponent(url.lastPathComponent)
            try fileManager.copyItem(at: url, to: destinationURL)
        }
    } catch {
        print("Error: \(error)")
    }
}

위의 코드에서 sourceDirectory는 삭제할 디렉토리의 경로이고, destinationDirectory는 파일을 복사할 경로입니다. 해당 함수는 trycatch를 사용하여 파일 복사 중 발생할 수 있는 에러를 처리하고 있습니다.

원본 삭제 로그 기록하기

원본 디렉토리를 삭제한 뒤에는 해당 삭제를 로그에 남기는 것이 좋습니다. 아래는 디렉토리 삭제 시 원본 위치와 삭제 시간을 로그에 남기는 Swift 코드 예제입니다.

func logDirectoryDeletion(directory: URL) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let deletionTime = dateFormatter.string(from: Date())

    let logMessage = "Deleted directory: \(directory.path) at \(deletionTime)"
    // 로그 작성 코드 (예: 파일에 로그 작성)
    print(logMessage)
}

위의 코드에서 directory는 삭제된 디렉토리의 경로이고, logMessage는 로그에 남길 메시지입니다. 이 메시지는 파일에 로그를 작성하거나 다른 로그 시스템에 전송될 수 있습니다.

이제 디렉토리를 삭제할 때 위의 함수를 호출하여 파일을 복사하고 삭제된 디렉토리에 대한 로그를 남길 수 있습니다.

이상으로 Swift에서 디렉토리 삭제 시 파일을 복사하고 원본 삭제를 로그에 기록하는 방법에 대해 알아보았습니다. 관련하여 궁금한 점이 있다면 참고 자료를 참조해 주세요.