How to Cancel Alamofire.Upload

How to cancel Alamofire.upload

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()

Cancel a request Alamofire

Alamofire 4 / Swift 3 / Xcode 8

You can cancel a single request as below:

1 - First get the request:

let request = Alamofire.SessionManager.default.request(path!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: createHeader()).responseJSON { response in
switch response.result {
case .success(let data):
success(data as AnyObject?)
case .failure(let error) :
failure(error as NSError)
}
}

2 - Then, in your viewDidDisappear, just call:

request.cancel()


You can cancel all requests as below:

Alamofire.SessionManager.default.session.getTasksWithCompletionHandler { (sessionDataTask, uploadData, downloadData) in
sessionDataTask.forEach { $0.cancel() }
uploadData.forEach { $0.cancel() }
downloadData.forEach { $0.cancel() }
}

Alamofire cancel a request out of multiple requests

According to the documentation cancel would:

Cancels the underlying task, producing an error that is passed to any registered response handlers.

Therefore, add a response handler to your request and see whether error messages are passed to them. If so, it means that the cancel operates correctly.

Alamofire 3.5.1 crashed when cancel the upload request

I find the root cause of my problem is the response.data is 0 bytes NSData, so the parseFromData of protobuf failed:

upload.responseData(completionHandler: { (response) in

self.uploading = false

let resp = NewFileResp.parseFromData(response.data!)
})


Related Topics



Leave a reply



Submit