Alamofire,会话管理器限制重试次数

时间:2016-09-26 22:17:26

标签: ios swift alamofire

我正在使用Alamofire的SessionManager向我的API服务发出请求。

有没有办法限制Alamofire的重试次数?

我正在使用新的RequestAdapter和RequestTrier协议在Alamofire v4中提供重试机制。

我想将重试次数限制为5.如果在5次重试之后,则不应该执行新请求。

Selenium::WebDriver::Error::WebDriverError:

Unable to find Mozilla geckodriver. Please download the server from   
   https://github.com/mozilla/geckodriver/releases and place it   
 somewhere on your PATH. More info at 
 https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver.

用法:

class VMRetrier: RequestAdapter, RequestRetrier {

public func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
    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 == 401 {
        VMLogger.shared.debug(message: "Trying to get a token")
        let _ = AuthService.shared.login(email: "a@a.com", password: "test34")
                           .then(execute: { (response) in
                                completion(true, 0.0)
                           })
    }
    else {
        completion(false, 0.0)
    }
} }

更新 alamofire中有一个新提交提供重试计数选项。Alamofire Commit

1 个答案:

答案 0 :(得分:4)

我用Alamofire的RequestRetrier协议解决了这个问题:

class Retrier: RequestRetrier {

    var defaultRetryCount = 4
    private  var requestsAndRetryCounts: [(Request, Int)] = []
    private  var lock = NSLock()

    private func index(request: Request) -> Int? {
        return requestsAndRetryCounts.index(where: { $0.0 === request })
    }

    func addRetryInfo(request: Request, retryCount: Int? = nil) {
        lock.lock() ; defer { lock.unlock() }
        guard index(request: request) == nil else { print("ERROR addRetryInfo called for already tracked request"); return }

        requestsAndRetryCounts.append((request, retryCount ?? defaultRetryCount))
    }

    func deleteRetryInfo(request: Request) {
        lock.lock() ; defer { lock.unlock() }
        guard let index = index(request: request) else { print("ERROR deleteRetryInfo called for not tracked request"); return }

        requestsAndRetryCounts.remove(at: index)
    }

    func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion){

        lock.lock() ; defer { lock.unlock() }

        guard let index = index(request: request) else { completion(false, 0); return }
        let (request, retryCount) = requestsAndRetryCounts[index]

        if retryCount == 0 {
            completion(false, 0)
        } else {
            requestsAndRetryCounts[index] = (request, retryCount - 1)
            completion(true, 0.5)
        }
    }
}

应该这样使用:

let manager = SessionManager()
let retrier = Retrier()
// ...
manager.retrier = retrier

然后

let request = manager.request(urlString, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers)

retrier.addRetryInfo(request: request)

request.response { r in
    self.retrier.deleteRetryInfo(request: request)
}.responseApiJSON { (r: DataResponse<JSONObject>) in
    // You code here
}