amirelo amirelo - 1 year ago 89
Swift Question

Cancel HTTP connection in iOS

I want to cancel

connection in background application.

Here is my code:

override func viewDidLoad() {
let url = URL(string: "my url")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard error == nil else {
guard let data = data else {
print("Data is empty")
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
} catch let error as NSError {



How do I cancel it anywhere in the program?

Answer Source

A way to do it is to keep a reference to the task instead of your local 'task'.

For instance, outside your viewDidLoad create:

var taskToReference: NSURLSessionDataTask!

Then change your code instead of let task = URLSession... instead do taskToReference = URLSession....

Now you have a reference var that you can use anywhere inside your view controller. Simply do taskToReference.cancel() anywhere in your class.

To make this something you can do from ANY view throughout your app, instead of creating the var in your class, create it in your AppDelegate and hold the reference there!

In your app delegate:

var taskToReference: NSURLSessionDataTask!

Then in your viewDidLoad, get a reference to app delegate before referencing the app-wide var:

let appDelegate = UIApplication.shared.delegate as! AppDelegate

Then change your initial task to:

appDelegate.taskToReference = URLSession...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download