The way to do this is to save the link to the task instead of the local task.
For example, outside your viewDidLoad, create:
var taskToReference: NSURLSessionDataTask!
Then change your code instead of let task = URLSession... and not taskToReference = URLSession...
You now have a var link that you can use anywhere in your controller. Just do taskToReference.cancel() anywhere in your class.
To do something that you can do from ANY view in the entire application, instead of creating var in your class, create it in your AppDelegate and save the link here!
In your application deletion:
var taskToReference: NSURLSessionDataTask!
Then, in your DidLoad view, get the link to the application delegate before referring to the public var:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
Then change your initial task to:
appDelegate.taskToReference = URLSession...
source share