How to find and cancel a task in NSURLSession?

本秂侑毒 提交于 2019-11-29 01:35:06

To get tasks list you can use NSURLSession's method

- (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.URL for returned tasks to find the one you want to cancel.

annu

Hope below code help.

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

Swift 3.0 version of @Avt's answer to get the task list. Use 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.

I suggest two methods:

  1. Put the list of NSURLSessionTask in 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 NSURLSessionTask as global variables so you can access to cancel it anywhere in your class.

I think you should do this...

First, keep track of your requests per xib

var download_requests = [NSURLSession]()

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

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
    // ....
  }
}

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

  override func viewDidDisappear(animated: Bool)
  {
    super.viewDidDisappear(animated)
    //stop all download requests
    for request in download_requests
    {
      request.invalidateAndCancel()
    }
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!