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?
If you want to cancel the request, you need to trace the requests made and try to cancel it. You can store it in an array and cancel every previous request stored. In your code you create a request: let request = Alamofire.
Using the Uploading MultiPartFormData example from the Alamofire README:
Alamofire.upload(
.POST,
"https://httpbin.org/post",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn")
multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
Here, upload.responseJSON
returns a Request
, which should allow you to assign it to something for cancellation later. For example:
let request = upload.responseJSON { ...
...
request.cancel()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With