Cancel All Operations + AFNetworking 3.0

我只是一个虾纸丫 提交于 2019-12-10 13:30:03

问题


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.


回答1:


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



回答2:


To cancel all dataTasks with NSURLSession:

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



回答3:


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

Isn’t that what you wanted?




回答4:


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


来源:https://stackoverflow.com/questions/39092183/cancel-all-operations-afnetworking-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!