[swift] Swift에서 파일 이동 시 파일을 압축하여 이동하는 방법

먼저, ZipArchive 라이브러리를 프로젝트에 추가해야 합니다. CocoaPods를 사용하고 있다면 Podfile에 다음을 추가하십시오:

pod 'ZipArchive'

그런 다음 터미널을 열고 다음 커맨드를 실행하여 라이브러리를 설치하십시오:

pod install

이제 파일을 압축하고 이동하는 코드를 작성할 시간입니다. 아래는 예시 코드입니다:

import ZipArchive

func moveAndCompressFile(sourcePath: String, destinationPath: String, zipFileName: String) {
    let zipFilePath = "\(destinationPath)/\(zipFileName)"
    
    let success = SSZipArchive.createZipFile(atPath: zipFilePath, withContentsOfFile: sourcePath)
    
    if success {
        // 압축 후 파일 이동
        do {
            try FileManager.default.removeItem(atPath: sourcePath)
            try FileManager.default.moveItem(atPath: zipFilePath, toPath: "\(destinationPath)/\(zipFileName)")
            print("파일 압축 및 이동이 완료되었습니다.")
        } catch {
            print("파일 압축 및 이동 중 에러 발생: \(error)")
        }
    } else {
        print("파일 압축 중 에러 발생")
    }
}

// 사용 예시
let sourcePath = "원본 파일 경로"
let destinationPath = "이동할 경로"
let zipFileName = "압축 파일명.zip"

moveAndCompressFile(sourcePath: sourcePath, destinationPath: destinationPath, zipFileName: zipFileName)

위 코드는 SSZipArchive를 사용하여 파일을 압축한 후, 원본 파일을 삭제하고 압축한 파일을 목적지로 이동합니다. 코드를 프로젝트에 맞게 수정하여 사용하시면 됩니다.

참고 자료: