[swift] Swift에서 디렉토리 삭제 후 파일 재압축하기

Swift를 사용하여 디렉토리를 삭제하고 파일을 재압축하는 방법에 대해 알아보겠습니다.

디렉토리 삭제하기

디렉토리를 삭제하기 전에 해당 디렉토리가 존재하는지 확인해야 합니다. 디렉토리가 존재하는지 확인하고 삭제하는 코드는 다음과 같습니다.

import Foundation

let fileManager = FileManager.default
let directoryPath = "/path/to/directory"

if fileManager.fileExists(atPath: directoryPath) {
    do {
        try fileManager.removeItem(atPath: directoryPath)
    } catch {
        print("Error: \(error)")
    }
} else {
    print("Directory does not exist")
}

위의 코드는 FileManager를 사용하여 디렉토리의 존재 여부를 확인하고 있다면 해당 디렉토리를 삭제합니다.

파일 재압축하기

파일을 재압축하려면 ZipArchiveSSZipArchive와 같은 라이브러리를 사용할 수 있습니다. 이러한 라이브러리를 사용하여 파일을 압축하는 방법은 다음과 같습니다.

import Foundation
import SSZipArchive

let sourcePath = "/path/to/source/file"
let destinationPath = "/path/to/destination/directory/archive.zip"

if SSZipArchive.createZipFile(atPath: destinationPath, withFilesAtPaths: [sourcePath]) {
    print("File compressed successfully")
} else {
    print("Error occurred while compressing file")
}

위의 코드는 SSZipArchive를 사용하여 파일을 압축합니다.

이제 Swift에서 디렉토리를 삭제하고 파일을 재압축하는 방법에 대해 알아보았습니다.

SSZipArchive 라이브러리 링크

[참고 문헌]

[1] NSHipster: ZipArchive