[使用Alamofire 5上传时访问encodingResult

问题描述 投票:0回答:1

我正在尝试将我的应用程序更新为Alamofire 5,但由于我使用它的方式有点hacking,所以我遇到了麻烦。

无论如何,我需要后台上传,而Alamofire并非真正旨在做到这一点。即便如此,我仍在使用它来创建包含多部分形式的格式正确的文件,以便稍后将其提供给OS以在后台上传。

我将在Alamofire 4中发布执行此操作的代码,我的问题是如何获取以前使用encodingResults获得的文件的url?

// We're not actually going to upload photo via alamofire. It does not offer support for background uploads.
// Still we can use it to create a request and more importantly properly formatted file containing multipart form
                Api.alamofire.upload(
                    multipartFormData: { multipartFormData in
                        multipartFormData.append(imageData, withName: "photo[image]", fileName: filename, mimeType: "image/jpg")
                },
                    to: "http://", // if we give it a real url sometimes alamofire will attempt the first upload. I don't want to let it get to our servers but it fails if I feed it ""
                    usingThreshold: UInt64(0), // force alamofire to always write to file no matter how small the payload is
                    method: .post,
                    headers: Api.requestHeaders,
                    encodingCompletion: { encodingResult in

                        switch encodingResult {
                        case .success(let alamofireUploadTask, _, let url):
                            alamofireUploadTask.suspend()
                            defer { alamofireUploadTask.cancel() }
                            if let alamofireUploadFileUrl = url {                                
                                // we want to own the multipart file to avoid alamofire deleting it when we tell it to cancel its task
                                let fileUrl = ourFileUrl
                                do {
                                    try FileManager.default.copyItem(at: alamofireUploadFileUrl, to: fileUrl)
                                    // use the file we just created for a background upload
                                } catch {
                                }
                            }
                        case .failure:
                            // alamofire failed to encode the request file for some reason
                        }
                    }
                )
alamofire alamofire-upload
1个回答
0
投票

分段编码已完全集成到Alamofire 5中现在异步的请求管道中。这意味着没有单独的步骤可以使用。但是,您可以直接使用MultipartFormData类型,就像在请求关闭中一样。

let data = MultipartFormData()
data.append(Data(), withName: "dataName")
try data.encode()
© www.soinside.com 2019 - 2024. All rights reserved.