具有修改后的有效负载的Alamofire重试请求

时间:2019-12-06 09:26:43

标签: swift alamofire

我一直在寻找当出现400错误时使用alamofire重试请求的方法,到目前为止,重试仍然有效,但是我不确定是否可以修改请求对象,以便在重试时具有一个更新的有效载荷。

欢迎任何建议和阅读材料的链接。

这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

文档讨论的是adapting and retrying requests,所以我认为这就是您要寻找的。

我写了以下内容,它按预期达到了adapt(_:)函数

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
    }

}