Cancel HTTP connection in iOS

I want to cancel the Http connection in the 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 can I cancel it anywhere in the program?

+5
source share
1 answer

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... 
+1
source

Source: https://habr.com/ru/post/1260280/


All Articles