Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire - how to have progress and completion closure with multipart upload

I managed to upload file with multipart-form-data Alamofire upload:

Alamofire.upload(.POST, "api.myservice.com", headers: myheaders, multipartFormData: { (multipartFormData:MultipartFormData) -> Void in

    multipartFormData.appendBodyPart(data: json, name: "metadata", mimeType: "application/json")
    multipartFormData.appendBodyPart(data: self.data, name: "document", fileName: "photo.png", mimeType: "image/png")

}, encodingMemoryThreshold: 10 * 1024 * 1024) { (result:Manager.MultipartFormDataEncodingResult) -> Void in
}

but I can't see a way to track upload progress and have completion block called after upload is completed (or failed). Is there a way to do this in Alamofire?

Note: I am aware that uploading with progress is possible, but I'm looking into multipart-form-data specifically.

like image 260
mixtly87 Avatar asked Dec 02 '15 21:12

mixtly87


1 Answers

Here is a way to have completion, failure and progress closures (thanks to my colleague for point me to the solution):

Alamofire.upload(.POST, absPath(), headers: headers(), multipartFormData: { (multipartFormData:MultipartFormData) -> Void in

    multipartFormData.appendBodyPart(data: json, name: "metadata", mimeType: "application/json")
    multipartFormData.appendBodyPart(data: self.data, name: "document", fileName: "photo.png", mimeType: "image/png")

    }, encodingMemoryThreshold: 10 * 1024 * 1024, encodingCompletion: { (encodingResult) -> Void in
        switch encodingResult {
        case .Success(let upload, _, _):
            upload.responseJSON { response in
                // success block
        }
            upload.progress { _, totalBytesRead, totalBytesExpectedToRead in
                let progress = Float(totalBytesRead)/Float(totalBytesExpectedToRead)
                // progress block
            }
        case .Failure(_):
            // failure block
        }
})
like image 81
mixtly87 Avatar answered Oct 09 '22 06:10

mixtly87