7

I have created a class HTTPServiceProvider inherited from AFURLSessionManager. Added below code to get the data.

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let manager = AFURLSessionManager(sessionConfiguration: configuration)
let dataTask = manager.dataTaskWithRequest(request) { (response, responseObject, error) in
         //Perform some task
}
dataTask.resume()

I want to add dataTask to operationQueue provided by AFURLSesstionManger and cancel all the operation in some other class (BaseController.swift) before calling the same request again.

Tried this code but not working -

self.operationQueue.addOperationWithBlock{
     //Added above code
}

And inside BaseController.swift file , called -

HTTPServiceProvide.sharedInstance.operationQueue.cancelAllOperations

But its not working :(

Thanks.

kennytm
  • 469,458
  • 94
  • 1,022
  • 977
ranjit.x.singh
  • 257
  • 3
  • 9

4 Answers4

6

For me best way to cancel all request is:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //manager should be instance which you are using across application
[manager.session invalidateAndCancel];

this approach has one big advantage: all your requests that are executing will call failure block. I mean this one for example:

        [manager GET:url
        parameters:nil
          progress:^(NSProgress * _Nonnull downloadProgress) {
              code
          } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              code
          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              //this section will be executed
          }];

2 things you need to know:

  • it will cancel request performed only with this exact instance of AFHTTPSessionManager you will use for invalidateAndCancel
  • after cancel all requests you have to init new instance of AFHTTPSessionManager - when you tried to make request with old one you will get exception
Łukasz Duda
  • 159
  • 1
  • 4
4

To cancel all dataTasks with NSURLSession:

manager.session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
    dataTasks.forEach { $0.cancel() }
}
Cœur
  • 32,421
  • 21
  • 173
  • 232
1

Maybe use AFURLSessionManager // Invalidates the managed session, optionally canceling pending tasks. - (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks

Isn’t that what you wanted?

leviathan
  • 10,700
  • 5
  • 39
  • 39
0

I created an array of tasks:

var tasks = [URLSessionDataTask]()

then appended the dataTask which all I want to cancel before making new http request:

tasks.append(dataTask)

And to cancel all the operations, I used:

func cancelPreviousRequest() {
    for task in tasks
       (task as URLSessionTask).cancel()
    }
    tasks.removeAll()
}
GoRoS
  • 4,445
  • 2
  • 37
  • 57
ranjit.x.singh
  • 257
  • 3
  • 9