[swift] Swift에서 디렉토리 삭제 시 파일 복사 내역 기록하기

Swift에서 디렉토리를 삭제할 때, 해당 디렉토리의 파일을 복사하여 기록하는 방법에 대해 알아보겠습니다. 이를 통해 파일 복사 내역을 추적하고, 데이터 손실을 방지할 수 있습니다.

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

이 예시에서는 FileManager 클래스를 사용하여 디렉토리 삭제 전 파일을 복사하는 방법을 보여드리겠습니다.

import Foundation

func copyFilesBeforeDeletion(directoryPath: String, targetDirectoryPath: String) {
    let fileManager = FileManager.default
    do {
        let files = try fileManager.contentsOfDirectory(atPath: directoryPath)
        for file in files {
            let sourceURL = URL(fileURLWithPath: directoryPath).appendingPathComponent(file)
            let destinationURL = URL(fileURLWithPath: targetDirectoryPath).appendingPathComponent(file)
            try fileManager.copyItem(at: sourceURL, to: destinationURL)
        }
    } catch {
        print(error)
    }
}

위의 코드를 사용하면 원본 디렉토리의 파일들을 목적 디렉토리에 복사할 수 있습니다.

참고 자료

  1. Swift FileManager Documentation - FileManager 클래스에 대한 공식 문서
  2. Swift - Directories and Files Manipulation - Swift에서 디렉토리 및 파일 다루기에 대한 자세한 내용

위의 예시를 통해, Swift에서 디렉토리를 삭제하기 전에 파일을 복사하여 기록하는 방법을 살펴보았습니다.