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.
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:
To cancel all dataTasks with NSURLSession:
manager.session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
dataTasks.forEach { $0.cancel() }
}
Maybe use AFURLSessionManager
// Invalidates the managed session, optionally canceling pending tasks.
- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks
Isn’t that what you wanted?
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With