Reputation: 621
I have been looking at making use of alamofire to retry a request when I get a certain 400 error and so far the retry works however I am not sure if it is possible to modify the request object so that when retrying it has an updated payload.
Any suggestions and links to reading material are welcome.
Here is my code :
class HTTP412Retrier: RequestRetrier, RequestAdapter {
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
print("called") // this is not being printed
return urlRequest
}
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) {
if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 412 {
completion(request.retryCount < 3, 0.0)
} else {
completion(false, 0.0)
}
}
}
Upvotes: 0
Views: 397
Reputation: 1440
The docs talk about adapting and retrying requests so I assume this would be what you are looking for.
I've written the following and it hits the adapt(_:)
function as expected
import UIKit
import Alamofire
class ViewController: UIViewController {
let sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default)
override func viewDidLoad() {
super.viewDidLoad()
sessionManager.adapter = AccessTokenAdapter(accessToken: "1234")
sessionManager.request("http://example.com")
}
}
class AccessTokenAdapter: RequestAdapter {
private let accessToken: String
init(accessToken: String) {
self.accessToken = accessToken
}
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
var urlRequest = urlRequest
guard let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix("https://example.com") else { return urlRequest }
urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
return urlRequest
}
}
Upvotes: 1