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.
A
There's a separate method in Alamofire to upload. Please check their documentation here.
They have sub-sections
Which describes uploading.
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.
As @cnoon said you can use upload method to track progress with some modifications. Here is what exactly worked with me:
let jsonData = NSJSONSerialization.dataWithJSONObject(jsonObject, options: .PrettyPrinted)
Alamofire.upload(.POST, "API URL String", headers: ["Content-Type": "application/json"], data: jsonData)
.validate()
.responseJSON(completionHandler: { (response: Response<AnyObject, NSError>) in
//Completion handler code
})
.progress({ (bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) in
//Progress handler code
})
Note that you must set the "Content-Type" http header field value to "application/json" if the data is formatted as json to be decoded correctly at the backend.