Cancel a request Alamofire
Asked Answered
P

6

35

I am sending a request which is triggered based on timer. But if I press the back button the request still seems to be active and the response in turns crashes the app. Kindly suggest a way to cancel the request.

Using Xcode 8.2.1 Swift 3

Here is the sample request :

Alamofire.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)
    }
}

Even tried invalidating the timer on viewDidDisappear but to no help.

Thanks !!

Pernas answered 5/1, 2017 at 5:53 Comment(2)
Please check #33000392Angeloangelology
@ImadAli . That is not helpful as invalidating would need to reinitialize the manage and i will not be able to make further calls as of.Pernas
P
59

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() }
}
Parish answered 15/6, 2017 at 1:44 Comment(0)
R
22

did you try this solution:

let sessionManager = Alamofire.SessionManager.default 
sessionManager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in 
dataTasks.forEach { $0.cancel() } 
uploadTasks.forEach { $0.cancel() } 
downloadTasks.forEach { $0.cancel() } 
}

i also add a check to verify if is this the request that i want to cancel:

dataTasks.forEach
            {
                if ($0.originalRequest?.url?.absoluteString == url)
                {
                    $0.cancel()
                }
            }
Ranchero answered 27/3, 2017 at 9:23 Comment(0)
C
6

SWIFT 5

Alamofire.Session.default.session.getTasksWithCompletionHandler({ dataTasks, uploadTasks, downloadTasks in
            dataTasks.forEach { $0.cancel() }
            uploadTasks.forEach { $0.cancel() }
            downloadTasks.forEach { $0.cancel() }
        })
Christianechristiania answered 9/8, 2020 at 11:10 Comment(0)
S
3

In case it helps anyone, in my case I had a RequestRetrier on the SessionManager that retried the request after it was canceled, so be sure to check there!

Sylvestersylvia answered 28/10, 2019 at 23:14 Comment(0)
F
2

How about this:

manager.session.invalidateAndCancel()
Forklift answered 28/2, 2019 at 8:31 Comment(0)
O
0

Alamofire 5 has a function on Session that cancels all requests:

Alamofire.Session.default.cancelAllRequests()

And another, withAllRequests, that can be used to perform an action on the set of active requests.

Docs: https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#operating-on-all-requests

Also, note that the Alamofire docs state that the underlying URLSession object:

should NOT be used to interact with the underlying URLSessionTasks. Doing so will break internal Alamofire logic that tracks those tasks.

Oreilly answered 15/11, 2023 at 4:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.