23

Is there any way I can for example say:

Alamofire.Manager.cancelAllRequests() or Alamofire.Manager.sharedInstance.cancelAllRequests()?

Of course it would be great if these requests especially in case of image download would only be paused for later when I'll cal the same URL but... I need at least to be able to cancel all requests at a global level. Some suggestions ?

In my app I have a wrapper above the Alamofire.request(.Post....) way of doing things so I would really appreciate not making me create or interact with Manager class in another way besides that specified above.

Fawkes
  • 3,831
  • 3
  • 22
  • 37

9 Answers9

67

cnoon's one-liner solution is great but it invalidates the NSURLSession and you need to create a new one.

Another solution would be this (iOS 7+):

session.getTasks { dataTasks, uploadTasks, downloadTasks in
    dataTasks.forEach { $0.cancel() }
    uploadTasks.forEach { $0.cancel() }
    downloadTasks.forEach { $0.cancel() }
}

Or if you target iOS 9+ only:

session.getAllTasks { tasks in
    tasks.forEach { $0.cancel() }
}
ldiqual
  • 15,015
  • 6
  • 52
  • 90
  • 4
    If you have not configured URLSession in alamofire, you can get default with `Alamofire.SessionManager.default.session` – Cfr Nov 03 '17 at 05:50
24

You should use the NSURLSession methods directly to accomplish this.

Alamofire.SessionManager.default.session.invalidateAndCancel()

This will call all your completion handlers with cancellation errors. If you need to be able to resume downloads, then you'll need to grab the resumeData from the request if it is available. Then use the resume data to resume the request in place when you're ready.

Keshu R.
  • 5,045
  • 1
  • 18
  • 38
cnoon
  • 16,575
  • 7
  • 58
  • 66
  • 3
    After calling this i am not able to make request again – Janak Thakkar Dec 21 '15 at 11:15
  • Once you invalidate a session, you need to create a new one in order to make additional requests. It's all in the [documentation](https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/#//apple_ref/occ/instm/NSURLSession/invalidateAndCancel). – cnoon Dec 21 '15 at 15:01
  • how can i create new ? – Janak Thakkar Dec 21 '15 at 15:02
  • 7
    the new call is: `Alamofire.SessionManager.default.session.invalidateAndCancel()` its refactored with https://github.com/Alamofire/Alamofire/commit/ade5a2e18e81f58d9ea39a4223f79e396578dc78#diff-47e97757a068c92a8406e56b15e64465 – miletliyusuf Apr 11 '18 at 08:17
16

Below Code stops the Requests in [Swift 3]:

Plus the code works for Alamofire v3 & v4 plus for iOS 8+.

func stopTheDamnRequests(){
    if #available(iOS 9.0, *) {
        Alamofire.SessionManager.default.session.getAllTasks { (tasks) in
            tasks.forEach{ $0.cancel() }
        }
    } else {
        Alamofire.SessionManager.default.session.getTasksWithCompletionHandler { (sessionDataTask, uploadData, downloadData) in
            sessionDataTask.forEach { $0.cancel() }
            uploadData.forEach { $0.cancel() }
            downloadData.forEach { $0.cancel() }
        }
    }
}

Simply Copy and paste the function.

Yash Bedi
  • 1,323
  • 17
  • 25
2

in completion to the @Loïs Di Qual you can check the request url and cancel (suspend, resume) the request that you need:

downloadTasks.forEach
            {
                if ($0.originalRequest?.url?.absoluteString == url)
                {
                    $0.cancel()
                }
            }
Constantin Saulenco
  • 2,353
  • 1
  • 22
  • 44
2

Swift 5+ & Alamofire 5.4.1

        AF.session.getAllTasks { (tasks) in
            tasks.forEach {$0.cancel() }
        }
Lakhdeep Singh
  • 1,212
  • 13
  • 9
1

If it helps, I got cnoon's answer to work on my own instance of an Alamofire.Manager. I have a singleton class called NetworkHelper which has a property called alamoFireManager, which handles all my network requests. I just call the NSURSession invalidateAndCancel() on that alamoFireManager property, reset my manager in setAFconfig(), then I'm good to go.

class NetworkHelper {

private var alamoFireManager : Alamofire.Manager!

class var sharedInstance: NetworkHelper {
    struct Static {
        static var instance: NetworkHelper?
        static var token: dispatch_once_t = 0
    }

    dispatch_once(&Static.token) {
        Static.instance = NetworkHelper()
    }

    return Static.instance!
}
init(){
    setAFconfig()
}

func setAFconfig(){
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForResource = 4
    configuration.timeoutIntervalForRequest = 4
    alamoFireManager = Alamofire.Manager(configuration: configuration)
}
func cancelAllRequests() {
    print("cancelling NetworkHelper requests")
    alamoFireManager.session.invalidateAndCancel()
    setAFconfig()
}
iantheparker
  • 239
  • 3
  • 11
1

In Swift 2.2

let session = Alamofire.Manager.sharedInstance.session
session.getAllTasksWithCompletionHandler() { tasks in
    tasks.forEach { $0.cancel() }
}
sazzad
  • 5,740
  • 6
  • 25
  • 42
Diego Carrera
  • 2,245
  • 1
  • 13
  • 16
1

How to stop the Api calling Alomofire in swift

class func StopAPICALL()  {
        let sessionManager = Alamofire.SessionManager.default
        sessionManager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
            dataTasks.forEach { $0.cancel() }
            uploadTasks.forEach { $0.cancel() }
            downloadTasks.forEach { $0.cancel() }
        }
    }
Kostas Charitidis
  • 2,991
  • 1
  • 12
  • 23
1

In Alamofire5, you can use:

    /// cancel all request in APIManager session
    /// - Parameter completion: Closure to be called when all `Request`s have been cancelled.
    func cancelAllRequest(completion: (() -> Void)? = nil) {
        self.session.cancelAllRequests(completion: completion)
    }
Heaven
  • 491
  • 3
  • 11