ios 如何在 NSURLSession 中查找和取消任务?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23518690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:05:25  来源:igfitidea点击:

How to find and cancel a task in NSURLSession?

iosobjective-cnetworkingnsurlsession

提问by Rostyslav Druzhchenko

I'm using an NSURLSessionobject to load images in my application. That could be loading several images simultaneously.

我正在使用一个NSURLSession对象在我的应用程序中加载图像。这可能是同时加载多个图像。

In some moments I need to cancel the loading of one specific image and continue loading others.

在某些时候,我需要取消加载一个特定图像并继续加载其他图像。

Could you suggest the correct way to do that?

你能建议正确的方法吗?

回答by Avt

To get tasks list you can use NSURLSession's method

要获取任务列表,您可以使用 NSURLSession 的方法

- (void)getTasksWithCompletionHandler:(void (^)(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks))completionHandler;

Asynchronously calls a completion callback with all outstanding data, upload, and download tasks in a session.

使用会话中所有未完成的数据、上传和下载任务异步调用完成回调。

Then check task.originalRequest.URLfor returned tasks to find the one you want to cancel.

然后检查task.originalRequest.URL返回的任务以找到要取消的任务。

回答by annu

Hope below code help.

希望下面的代码有帮助。

-(IBAction)cancelUpload:(id)sender {    
    if (_uploadTask.state == NSURLSessionTaskStateRunning) {
        [_uploadTask cancel];
     }
  }

回答by pedrouan

Swift 3.0version of @Avt'sanswer to get the task list. Use getTasksWithCompletionHandler.

Swift 3.0版本的@Avt获取任务列表答案。使用getTasksWithCompletionHandler

func getTasksWithCompletionHandler(_ completionHandler: @escaping ([URLSessionDataTask], 
   [URLSessionUploadTask], 
   [URLSessionDownloadTask]) -> Void) {     
}

The returned arrays contain any tasks that you have created within the session, not including any tasks that have been invalidated after completing, failing, or being cancelled.

返回的数组包含您在会话中创建的任何任务,不包括任何在完成、失败或被取消后失效的任务。

回答by inokey

Based on all the answers below, I'd go for something like this:

根据下面的所有答案,我会选择这样的:

Swift 5

斯威夫特 5

 func cancelTaskWithUrl(_ url: URL) {
    URLSession.shared.getAllTasks { tasks in
      tasks
        .filter { 
var download_requests = [NSURLSession]()
.state == .running } .filter {
let s = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
if let url = NSURL(string: "http://my.url.request.com")
{
  download_requests.append(s)
  s.dataTaskWithURL(url)
  { (data, resp, error) -> Void in
    // ....
  }
}
.originalRequest?.url == url }.first? .cancel() } }

You also probably want to account for your task completion handler, since canceling the task will result Errorin that completion handler.

您可能还想考虑您的任务完成处理程序,因为取消任务将导致Error该完成处理程序。

回答by Nhon Nguyen

I suggest two methods:

我建议两种方法:

  1. Put the list of NSURLSessionTaskin an array. In case you don't know exactly how many images you would get. Though you have to know the index of session in order to cancel it.
  2. If you get a limited number of images. Just use a set of NSURLSessionTaskas global variables so you can access to cancel it anywhere in your class.
  1. 将 的列表放入NSURLSessionTask数组中。如果你不知道你会得到多少张图片。尽管您必须知道会话的索引才能取消它。
  2. 如果您获得的图像数量有限。只需使用一组NSURLSessionTask作为全局变量,这样您就可以在班级的任何地方访问以取消它。

回答by Who Is The Baddest

I think you should do this...

我认为你应该这样做...

First, keep track of your requests per xib

首先,跟踪每个 xib 的请求

  override func viewDidDisappear(animated: Bool)
  {
    super.viewDidDisappear(animated)
    //stop all download requests
    for request in download_requests
    {
      request.invalidateAndCancel()
    }
  }

Then, whenever you make a request, append your request to your array like so,

然后,每当您提出请求时,将您的请求附加到您的数组中,

##代码##

Then whenever you want to cancel any outstanding requests, (let's say on viewDidDisappear), do

然后,每当您想取消任何未完成的请求时,(假设在 viewDidDisappear 上),请执行

##代码##