取消所有操作+ AFNetworking 3.0

ran*_*ngh 6 ios swift afnetworking-3

我创建了一个继承自AFURLSessionManager的类HTTPServiceProvider.添加以下代码以获取数据.

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

我想将dataTask添加到AFURLSesstionManger提供的operationQueue中,并在再次调用相同的请求之前取消其他类(BaseController.swift)中的所有操作.

试过这段代码但没有工作 -

self.operationQueue.addOperationWithBlock{
     //Added above code
}
Run Code Online (Sandbox Code Playgroud)

在BaseController.swift文件中,调用 -

HTTPServiceProvide.sharedInstance.operationQueue.cancelAllOperations
Run Code Online (Sandbox Code Playgroud)

但它没有工作:(

谢谢.

Łuk*_*uda 5

对我来说,取消所有请求的最佳方法是:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //manager should be instance which you are using across application
[manager.session invalidateAndCancel];
Run Code Online (Sandbox Code Playgroud)

这种方法有一个很大的优势:您正在执行的所有请求都将调用失败块。我的意思是例如:

        [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
          }];
Run Code Online (Sandbox Code Playgroud)

您需要了解的2件事:

  • 它将取消仅对此AFHTTPSessionManager的确切实例执行的请求,您将使用该实例执行invalidateAndCancel
  • 取消所有请求后,您必须初始化AFHTTPSessionManager的新实例-当您尝试使用旧的实例进行请求时,您将获得异常


Cœu*_*œur 3

使用 NSURLSession 取消所有数据任务:

manager.session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
    dataTasks.forEach { $0.cancel() }
}
Run Code Online (Sandbox Code Playgroud)