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



后台上传有可能与alamofire api和URLession的一些改编一起使用,并且使用以下代码:

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 5 不支持后台URLSessionConfiguration,但您发布的代码只是分段上传,仍然支持得很好。

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

Alamofire确实可以使用后台任务,这可以给你时间完成上传。您可以在此处阅读更多内容。

相关内容

  • 没有找到相关文章

最新更新