Alamofire POST请求进展

我正在使用Alamofire来执行POST请求。 由于此POST请求可能需要一段时间,我想跟踪进度并将其显示为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块只在post请求结束后才被调用,而不是多次调用来实际跟踪进度。 println(“ENTER .PROGRESSS”)只被调用一次(最后)

我怎样才能让.progress与Alamofire.request POST一起工作?

另外:我的参数包括一个base64编码的图像string。 我正在使用后端Ruby on Rails来处理图像。 这是需要相当一段时间的过程。

你可以做的是首先使用ParameterEncoding枚举来生成HTTPBody数据。 然后,您可以将这些数据提取出来并传递给Alamofire upload方法。 这里有一个相同函数的修改版本,可以在操场上编译,而是使用uploadfunction。

 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最初在他上面的评论中提到过。

正如@cnoon所说,你可以使用上传方法来跟踪进度,并进行一些修改。 这是什么与我一起工作:

 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 }) 

请注意 ,如果数据格式为json,则必须将“Content-Type” http标头字段值设置为“application / json” ,以便在后端正确解码。

Alamofire有一个独立的方法来上传。 请在这里查看他们的文档。

他们有子部分

  1. 上传进度
  2. 上传MultipartFormData

其中描述了上传。