2

I know that invoking getTasksWithCompletionHandler on an NSURLSession:

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

However, from experimentation, I can see the data, upload, and download task arrays returned by the method;

func getTasksWithCompletionHandler(_ completionHandler: ([NSURLSessionDataTask], [NSURLSessionUploadTask], [NSURLSessionDownloadTask]) -> Void)

are in fact only show executing tasks. I.e., tasks which have received resume().

This can be seen by copy pasting this code in a Playground:

import UIKit
import XCPlayground

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let url = NSURL(string: "http://jsonplaceholder.typicode.com")
let request: NSURLRequest = NSURLRequest(URL: url!)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
    NSLog("Done")
})

session.getAllTasksWithCompletionHandler { (tasks:[NSURLSessionTask]) -> Void in
    NSLog("\(tasks)")
    XCPlaygroundPage.currentPage.finishExecution()
}

//task.resume()

Note that getTasksWithCompletionHandler and getAllTasksWithCompletionHandler - the latter released in iOS 9 - seem to only differ in the signature of the completion closure.

Also, somewhat tantalisingly, NSURLSessionTask has a state property NSURLSessionTaskState that gives us Running, Suspended, Canceling, Completed.

Is there a way to access the list of non-executing tasks; those that have been aded to the NSURLSession yet have not resumed?

Max MacLeod
  • 26,115
  • 13
  • 104
  • 132
  • Apple : "Each task starts out in a suspended state. After your app calls resume on the task, it begins downloading the specified resource. " You have to call resume() method once you have created the task objects. By default tasks are in suspended state. – Aditya Gaonkar Dec 24 '15 at 15:47
  • 1
    How can I access that array of suspended tasks? – Max MacLeod Dec 24 '15 at 16:34
  • In URLSession you will get the getallTasks method which givess all suspended task array. – Anjan Nov 14 '18 at 09:23

0 Answers0