amirelo amirelo - 14 days ago 5
Swift Question

Cancel HTTP connection in iOS

I want to cancel

Http
connection in background application.

Here is my code:

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

task.resume()

}


How do I cancel it anywhere in the program?

Answer

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