stop HTTP request
In the normal application which is totally based on the Internet means not the offline mode, this types of an application always connect to the internet and make a Http or Https request on every click on the event in an application.
Some times user don’t want to stay in one controller on clicking the Http request and move to another controller due to that reason two HTTP request going on and response becomes slow so we need to discard the previous network request.
For this, we need to do some
1: Make a queue of the network request.
2: Discard the previous request.
For this, we need to do this
write this code in every UIViewController
1 2 3 4 5 6 7 8 9 |
override func viewWillDisappear(_ animated: Bool) { let sessionManager = Alamofire.SessionManager.default sessionManager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in dataTasks.forEach { $0.cancel() } uploadTasks.forEach { $0.cancel() } downloadTasks.forEach { $0.cancel() } self.timer.invalidate() } } |
3: You can check whether it is working or not for this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Alamofire.request(urlString,method: HTTPMethod.post,parameters:params,headers: headers).validate().responseJSON { response in switch response.result { case .success(let resultData): taskCallback(1,resultData as AnyObject) break case .failure(let error): if !Connectivity.isConnectedToInternet(){ taskCallback(2, "" as AnyObject) } else{ print(error.localizedDescription) taskCallback(3, error.localizedDescription as AnyObject) } break; } } |
Note: error.localizeddescription will return “cancelled”
Now you this in every controller for discard the previous request.