Search Your Question

How to cancel alamofire api request?

Ans:

You can cancel a single request as below:
1 - First get the request:
let request = Alamofire.SessionManager.default.request(path!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: createHeader()).responseJSON { response in
    switch response.result {
    case .success(let data):
        success(data as AnyObject?)
    case .failure(let error) :
        failure(error as NSError)
    }
}
2 - Then, in your viewDidDisappear, just call:
request.cancel()

You can cancel all requests as below:
Alamofire.SessionManager.default.session.getTasksWithCompletionHandler { (sessionDataTask, uploadData, downloadData) in
    sessionDataTask.forEach { $0.cancel() }
    uploadData.forEach { $0.cancel() }
    downloadData.forEach { $0.cancel() }
}

According to different alamofire and swift version, above code may change little bit.

No comments:

Post a Comment

Thanks