I am uploading images on server via Alamofire.upload
as multipart data. Unlike Alamofire.request
it's not returning Request
object, which I usually use to cancel requests.
But it's very reasonable to be able to cancel such a consuming requests like uploading. What are the options for this in Alamofire?
I'm afraid you can't, according to the Alamofire source code the
upload
function returns anRequest
type in all of its overloads except in these that support MultipartFormData see the following code:It's recommended when you are writing client-side code, use
multipart/form-data
when your form includes any<input type="file">
elements.So if you want to just upload an image to the server you can use the another
upload
function overloads that returns anRequest
object and you can cancel it like in this ways proposed in the Alamofire documentation:I hope this help you.
Using the Uploading MultiPartFormData example from the Alamofire README:
Here,
upload.responseJSON
returns aRequest
, which should allow you to assign it to something for cancellation later. For example:It's possible to prepare a closure, and transfer a request out of "encodingCompletion"
In my case I created "sessionManager" instance in my API class and assigned Alamofire's session manager with configuration to it.
Then I could create a method to cancel any current request type. Note that here "(_, uploadTasks, _)" you can also have "dataTasks" & "downloadTasks" which you can also cancel if you want "(dataTasks, uploadTasks, downloadTasks)"
You can also have smth like this:
Where "CancelRequestType" is enum. So you can call the method like
API.cancel(request: .UploadTask)