gpt4 book ai didi

ios - 有进度的 Alamofire POST 请求

转载 作者:搜寻专家 更新时间:2023-10-30 22:10:46 24 4
gpt4 key购买 nike

我正在使用 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 block 仅在发布请求结束后才被调用,而不是被多次调用以实际跟踪进度。 println("ENTER .PROGRESS") 只调用一次(最后)

如何使 .progress 与 Alamofire.request POST 一起工作?

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

最佳答案

您可以做的是首先使用 ParameterEncoding 枚举来生成 HTTPBody 数据。然后您可以提取该数据并将其传递给 Alamofire upload 方法。这是在 playground 中编译的相同函数的修改版本,而是使用 upload 函数。

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 在他上面的评论中最初提到的那样,这肯定会有进展更新。

关于ios - 有进度的 Alamofire POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28267796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com