[swift] PromiseKit를 이용한 파일 업로드 및 다운로드

PromiseKit은 Swift로 비동기 작업을 처리할 수 있는 강력한 라이브러리입니다. 이번 포스트에서는 PromiseKit을 사용하여 파일 업로드와 다운로드 작업을 처리하는 방법에 대해 알아보겠습니다.

파일 업로드

파일 업로드를 위해서는 서버에 파일을 전송해야합니다. PromiseKit은 비동기 작업을 처리하는데 사용되며, 파일 업로드 작업 역시 비동기로 처리되어야 합니다.

먼저, PromiseKit을 프로젝트에 추가해주어야 합니다. 이를 위해 CocoaPods를 사용할 수 있습니다. Podfile에 다음과 같이 추가한 후, pod install 명령어를 실행하여 PromiseKit을 설치합니다.

pod 'PromiseKit', '~> 6.13'

다음으로, 파일 업로드를 위한 함수를 작성합니다. 예를 들어, uploadFile 함수를 작성해보겠습니다.

import PromiseKit

func uploadFile(fileURL: URL) -> Promise<String> {
    return Promise { seal in
        // 파일 업로드 작업을 여기에 구현합니다.
        // 성공 시 결과를 fulfill하고, 실패 시 오류를 reject합니다.
        
        let uploadTask = URLSession.shared.uploadTask(with: request, fromFile: fileURL) { data, response, error in
            if let error = error {
                seal.reject(error)
            } else {
                // 성공 시 업로드된 파일의 URL을 fulfill합니다.
                let fileURL = "https://example.com/uploads/\(fileURL.lastPathComponent)"
                seal.fulfill(fileURL)
            }
        }
        
        uploadTask.resume()
    }
}

위의 코드에서는 URL 세션을 사용하여 파일을 업로드하는 작업을 구현했습니다. 업로드된 파일의 URL은 Promise의 결과로 반환됩니다.

이제 파일 업로드 함수를 호출하여 파일을 업로드하는 예시 코드를 작성해보겠습니다.

let fileURL = URL(fileURLWithPath: "path/to/file.txt")
uploadFile(fileURL: fileURL)
    .done { fileURL in
        print("File uploaded:", fileURL)
    }
    .catch { error in
        print("Error:", error)
    }

파일 업로드 작업이 성공하면 done 핸들러가 호출되어 업로드된 파일의 URL이 출력됩니다. 실패할 경우 catch 핸들러가 호출되어 오류가 출력됩니다.

파일 다운로드

파일 다운로드 역시 PromiseKit을 사용하여 비동기로 처리할 수 있습니다.

다운로드를 위한 함수를 작성해보겠습니다. 예를 들어, downloadFile 함수를 작성해보겠습니다.

import PromiseKit

func downloadFile(fileURL: URL, saveToURL destinationURL: URL) -> Promise<Void> {
    return Promise { seal in
        let downloadTask = URLSession.shared.downloadTask(with: fileURL) { location, response, error in
            if let error = error {
                seal.reject(error)
            } else {
                // 이동된 파일을 지정된 위치로 복사합니다.
                do {
                    try FileManager.default.moveItem(at: location, to: destinationURL)
                    seal.fulfill(())
                } catch {
                    seal.reject(error)
                }
            }
        }
        
        downloadTask.resume()
    }
}

위의 코드에서는 URL 세션을 사용하여 파일을 다운로드하는 작업을 구현했습니다. 다운로드된 파일은 지정된 위치로 이동되며, 이동이 성공하면 Promise가 fulfill됩니다.

다음은 파일 다운로드 함수를 호출하여 파일을 다운로드하는 예시 코드입니다.

let fileURL = URL(string: "https://example.com/files/file.txt")!
let destinationURL = URL(fileURLWithPath: "path/to/save/file.txt")
downloadFile(fileURL: fileURL, saveToURL: destinationURL)
    .done {
        print("File downloaded and saved:", destinationURL)
    }
    .catch { error in
        print("Error:", error)
    }

파일 다운로드 작업이 성공하면 done 핸들러가 호출되어 다운로드된 파일의 위치가 출력됩니다. 실패할 경우 catch 핸들러가 호출되어 오류가 출력됩니다.

이렇게 PromiseKit를 사용하여 파일 업로드 및 다운로드 작업을 처리할 수 있습니다. PromiseKit은 Swift에서 비동기 작업을 효율적으로 처리하기 위한 강력한 도구입니다.

참고: PromiseKit 공식 문서