[swift] Swift에서 디렉토리 생성 후 파일 압축하기

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

디렉토리 생성하기

먼저, 디렉토리를 생성하는 방법부터 살펴보겠습니다. Swift에서 디렉토리를 생성하려면 FileManager 클래스를 사용합니다. 아래의 예제 코드를 통해 디렉토리 생성 방법을 확인해보세요.

import Foundation

let fileManager = FileManager.default
let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("MyDirectory")

do {
    try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
    print(error)
}

위 예제 코드에서는 FileManager를 사용하여 문서 디렉토리 내에 “MyDirectory”라는 디렉토리를 생성하고 있습니다.

파일 압축하기

이제, 생성한 디렉토리에 파일을 압축하는 방법을 알아보겠습니다. Swift에서는 ZipArchive와 같은 라이브러리를 사용하여 파일을 압축할 수 있습니다.

import Zip

let sourceURLs = [URL(fileURLWithPath: "path_to_file1"), URL(fileURLWithPath: "path_to_file2")]
let destinationURL = URL(fileURLWithPath: "path_to_zip_file.zip")

do {
    try Zip.zipFiles(paths: sourceURLs, zipFilePath: destinationURL, password: nil, progress: { (progress) in
        print(progress)
    })
} catch {
    print("Something went wrong when zipping the files: \(error)")
}

위의 예제 코드에서는 Zip 라이브러리를 사용하여 파일을 압축하는 방법을 보여주고 있습니다.

이제, Swift에서 디렉토리 생성 및 파일 압축하는 방법을 알게 되었습니다.

더 자세한 내용은 FileManager - Apple Developer DocumentationZip - GitHub를 참고하세요.