Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire POST request with progress

I'm using Alamofire to do a POST request. As this POST request can take a while and I want to keep track of the progress and display it as a ProgressView.

Alamofire.request(.POST, ApiLink.create_post, parameters: parameters, encoding: .JSON)
        .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) -> Void in
            println("ENTER .PROGRESSS")
            println("\(totalBytesRead) of \(totalBytesExpectedToRead)")                
            self.progressView.setProgress(Float(totalBytesRead) / Float(totalBytesExpectedToRead), animated: true)
        }
        .responseJSON { (_, _, mydata, _) in 
            println(mydata)
        }

However, I've noticed that the .progress block only get called after the post request has ended instead of getting called multiple times to actually keep track of the progress. println("ENTER .PROGRESSS") gets called only once (at the end)

How can I make .progress works with Alamofire.request POST ?

Also : My parameters include a base64 encoded image string. I'm using a back-end Ruby on Rails to process the image. It's that process that is taking quite some time.

like image 982
fabdarice Avatar asked Feb 01 '15 20:02

fabdarice


1 Answers

What you can do instead is first use the ParameterEncoding enum to generate the HTTPBody data. Then you can pull that data out and pass it off to the Alamofire upload method. Here's a modified version of your same function that compiles in a playground and instead uses the upload function.

struct ApiLink {
    static let create_post = "/my/path/for/create/post"
}

let parameters: [String: AnyObject] = ["key": "value"] // Make sure this has your image as well

let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: ApiLink.create_post)!)
mutableURLRequest.HTTPMethod = Method.POST.rawValue

let encodedURLRequest = ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0
let data = encodedURLRequest.HTTPBody!

let progressView = UIProgressView()

Alamofire.upload(mutableURLRequest, data)
         .progress { _, totalBytesRead, totalBytesExpectedToRead in
             println("ENTER .PROGRESSS")
             println("\(totalBytesRead) of \(totalBytesExpectedToRead)")
             progressView.setProgress(Float(totalBytesRead) / Float(totalBytesExpectedToRead), animated: true)
         }
         .responseJSON { _, _, mydata, _ in
             println(mydata)
         }

This will certainly have progress updates as @mattt originally mentioned in his comment above.

like image 104
cnoon Avatar answered Sep 29 '22 11:09

cnoon