Alamofire POST请求正在进行 [英] Alamofire POST request with progress
问题描述
我正在使用Alamofire进行POST请求。
由于此POST请求可能需要一段时间,因此我想跟踪进度并将其显示为ProgressView。
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)
}
但是,我注意到 .progress块仅在发布请求结束后才被调用被多次调用以实际跟踪进度的过程。
println( ENTER .PROGRESSS)仅被调用一次(最后)
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)
如何使.progress起作用使用Alamofire.request POST吗?
How can I make .progress works with Alamofire.request POST ?
也:我的参数包括base64编码的图像字符串。我正在使用后端Ruby on Rails处理图像。就是这个过程,需要花费一些时间。
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.
推荐答案
您可以做的是首先使用 ParameterEncoding
枚举以生成HTTPBody数据。然后,您可以提取该数据并将其传递给Alamofire upload
方法。这是您在操场上编译的同一函数的修改版本,而是使用 upload
函数。
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)
}
这肯定会有进度更新,就像@mattt最初在上面的评论中提到的那样。
This will certainly have progress updates as @mattt originally mentioned in his comment above.
这篇关于Alamofire POST请求正在进行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!