如何用Alamofire 5处理后台上传?

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

有一个机会,后台上传的工作与一些适应alamofire api和URLSession的白色代码。

Alamofire.upload(
                multipartFormData: { multipartFormData in
                    multipartFormData.append(imageData, withName: "photo[image]", fileName: filename, mimeType: "image/jpg")
            },
                usingThreshold: UInt64(0), // force alamofire to always write to file no matter how small the payload is
                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 ""
                method: .post,
                headers: headers,
                encodingCompletion: { encodingResult in
                    switch encodingResult {
                    case .success(let alamofireUploadTask, _, let url):
                        alamofireUploadTask.suspend()
                        defer { alamofireUploadTask.cancel() }
                        if let alamofireUploadFileUrl = url {
                            var request = URLRequest(url: URL(string: "https://yourserver.com/photoUploadEndpoint")!)
                            request.httpMethod = "POST"
                            for (key, value) in alamofireUploadTask.request!.allHTTPHeaderFields! { // transfer headers from the request made by alamofire
                                request.addValue(value, forHTTPHeaderField: key)
                            }
                            // we want to own the multipart file to avoid alamofire deleting it when we tell it to cancel its task
                            // so copy file on alamofireUploadFileUrl to a file you control
                            // dispatch the request to the background session
                            // don't forget to delete the file when you're done uploading
                        } else {
                            // alamofire failed to encode the request file for some reason
                        }
                    case .failure:
                        // alamofire failed to encode the request file for some reason
                    }
            }
            )

不幸的是,这在Alamofire 5中是行不通的,有什么办法可以适应?

alamofire background-process urlsession nsurlsessionconfiguration
1个回答
0
投票

Alamofire 5不支持后台 URLSessionConfiguration的,但你发布的代码只是多部分上传,仍然支持得很好。

你围绕着上传的各种黑客行为应该重新评估一下新版的Alamofire。这真的没有任何意义。

Alamofire确实可以和后台任务一起工作,这可以给你时间完成上传。你可以阅读更多 此处.

© www.soinside.com 2019 - 2024. All rights reserved.