Fawkes
Fawkes

Reputation: 3941

iOS Alamofire stop all requests

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.

Upvotes: 25

Views: 25644

Answers (10)

kaushik
kaushik

Reputation: 1

If you want to create requst without any third party then you can create like this

    var userObj: LoginUser_Codable?

var dict = [String:Any]()

        dict["name"] =  "kaushik"
        dict["salary"] =  "123"
        dict["age"] =  "23"
        
        var request = URLRequest(url: URL(string: "https://dummy.restapiexample.com/api/v1/create")!)
        request.httpMethod = "POST"
        request.httpBody = try? JSONSerialization.data(withJSONObject: dict, options: [])
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        let session = URLSession.shared
        let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
            print(response!)
            do {
                let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
                print(json)
                
                if let data = json["data"] as? [String: Any]
                {
                    let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
                    let reqJSONStr = String(data: jsonData, encoding: .utf8)
                    let data = reqJSONStr?.data(using: .utf8)
                    let jsonDecoder = JSONDecoder()
                    let uObj = try jsonDecoder.decode(LoginUser_Codable.self, from: data!)
                    print(json)
                }
                

            } catch {
                print("error")
            }
        })

        task.resume()

Create Model

import Foundation
import UIKit

//MARK: - User
struct LoginUser_Codable: Codable
{
    var emailAddress : String?
    var firstName      : String?
    var id        : Int?
    var name    : String?
    
    
    enum CodingKeys: String, CodingKey {
        case id
        case emailAddress
        case firstName
        case name
        
    }
}

Upvotes: 0

Lakhdeep Singh
Lakhdeep Singh

Reputation: 1250

Swift 5+ & Alamofire 5.4.1

        AF.session.getAllTasks { (tasks) in
            tasks.forEach {$0.cancel() }
        }

Upvotes: 3

Heaven
Heaven

Reputation: 536

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

Upvotes: 1

cnoon
cnoon

Reputation: 16643

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.

Upvotes: 24

Praveen Reddy
Praveen Reddy

Reputation: 81


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

Upvotes: 1

Yash Bedi
Yash Bedi

Reputation: 1355

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.

Upvotes: 16

Constantin Saulenco
Constantin Saulenco

Reputation: 2383

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

Upvotes: 2

Diego Carrera
Diego Carrera

Reputation: 2355

In Swift 2.2

let session = Alamofire.Manager.sharedInstance.session
session.getAllTasksWithCompletionHandler() { tasks in
    tasks.forEach { $0.cancel() }
}

Upvotes: 1

ldiqual
ldiqual

Reputation: 15365

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

Upvotes: 68

iantheparker
iantheparker

Reputation: 239

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

Upvotes: 1

Related Questions