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

Swift로 개발을 하다보면 sometimes 디렉토리를 삭제해야할 때가 있습니다. 그러나 삭제하기 전에 디렉토리 안에 있는 파일들을 다른 곳에 백업해두고 싶을 수 있습니다. 이러한 경우를 위해 Swift에서 디렉토리를 삭제하기 전에 내부 파일들을 복사하는 방법에 대해 알아보겠습니다.

디렉토리 내의 파일 복사

먼저, 디렉토리 내의 파일을 복사하는 방법을 살펴봅시다. 아래의 코드는 디렉토리 내의 파일을 새로운 위치로 복사하는 방법을 보여줍니다.

import Foundation

func copyFiles(from sourceURL: URL, to destinationURL: URL) {
    let fileManager = FileManager.default
    do {
        let files = try fileManager.contentsOfDirectory(at: sourceURL, includingPropertiesForKeys: nil)
        for file in files {
            let destinationFileURL = destinationURL.appendingPathComponent(file.lastPathComponent)
            try fileManager.copyItem(at: file, to: destinationFileURL)
        }
    } catch {
        print("Error: \(error)")
    }
}

위의 코드는 FileManager 클래스를 사용하여 디렉토리 내의 파일을 순회하면서 새로운 위치로 복사합니다.

디렉토리 삭제 전 파일 복사

이제, 디렉토리를 삭제하기 전에 내부 파일들을 백업하는 방법을 살펴봅시다.

func backupDirectory(at sourceURL: URL, to destinationURL: URL) {
    let fileManager = FileManager.default
    do {
        try fileManager.createDirectory(at: destinationURL, withIntermediateDirectories: true, attributes: nil)
        let files = try fileManager.contentsOfDirectory(at: sourceURL, includingPropertiesForKeys: nil)
        for file in files {
            let destinationFileURL = destinationURL.appendingPathComponent(file.lastPathComponent)
            try fileManager.copyItem(at: file, to: destinationFileURL)
        }
    } catch {
        print("Error: \(error)")
    }
}

위의 코드는 먼저 백업할 새로운 디렉토리를 생성하고, 그 안에 원본 디렉토리 내의 파일들을 복사합니다.

결론

이제 당신은 Swift를 사용하여 디렉토리를 삭제하기 전에 파일을 백업하는 방법을 배웠습니다. 이를 통해 파일이 영구적으로 손실되는 것을 방지할 수 있으며, 안전하게 디렉토리를 삭제할 수 있게 될 것입니다.

참고문헌: