Cancel a request Alamofire

情到浓时终转凉″ 提交于 2019-11-30 10:47:24

问题


I am sending a request which is triggered based on timer. But if I press the back button the request still seems to be active and the response in turns crashes the app. Kindly suggest a way to cancel the request.

Using Xcode 8.2.1 Swift 3

Here is the sample request :

Alamofire.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)
    }
}

Even tried invalidating the timer on viewDidDisappear but to no help.

Thanks !!


回答1:


Alamofire 4 / Swift 3 / Xcode 8

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() }
}



回答2:


did you try this solution:

let sessionManager = Alamofire.SessionManager.default 
sessionManager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in 
dataTasks.forEach { $0.cancel() } 
uploadTasks.forEach { $0.cancel() } 
downloadTasks.forEach { $0.cancel() } 
}

i also add a check to verify if is this the request that i want to cancel:

dataTasks.forEach
            {
                if ($0.originalRequest?.url?.absoluteString == url)
                {
                    $0.cancel()
                }
            }



回答3:


How about this:

manager.session.invalidateAndCancel()



回答4:


In case it helps anyone, in my case I had a RequestRetrier on the SessionManager that retried the request after it was canceled, so be sure to check there!



来源:https://stackoverflow.com/questions/41478122/cancel-a-request-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!