Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel Alamofire.upload

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?

like image 471
user3537411 Avatar asked Jan 19 '16 23:01

user3537411


People also ask

How do I cancel a previous request in Swift?

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.


1 Answers

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()
like image 103
Paul Young Avatar answered Nov 25 '22 20:11

Paul Young