Cancel all operations + AFNetworking 3.0

I created an HTTPServiceProvider class inherited from AFURLSessionManager. Added code below to receive 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 a dataTask to the operationQueue provided by AFURLSesstionManger and cancel all operations in some other class (BaseController.swift) before invoking the same request again.

Tried this code but didn't work -

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

And inside the BaseController.swift file called -

 HTTPServiceProvide.sharedInstance.operationQueue.cancelAllOperations 

But its not working :(

Thanks.

+5
source share
4 answers

Cancel all tasks with NSURLSession:

 manager.session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in dataTasks.forEach { $0.cancel() } } 
+2
source

For me, the best way to cancel all requests 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 executed will cause a block of failures. I mean this, 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 cancels the request executed only with this exact instance of AFHTTPSessionManager, which you will use for invalidateAndCancel
  • after canceling all requests, you should start a new instance of AFHTTPSessionManager - when you try to make a request with the old one, you will get an exception
+2
source

I created an array of tasks.
var tasks = [URLSessionDataTask]()
then added a dataTask which is all I want to cancel before creating a new http request
tasks.append(dataTask)

And to cancel all operations, I used func cancelPreviousRequest(){ for task in tasks (task as URLSessionTask).cancel() } tasks.removeAll() }

0
source

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

Isn't that what you wanted?

0
source

All Articles