Alamofire:如何只重试一次请求

时间:2017-03-18 18:30:44

标签: count request alamofire retrypolicy

我正在采用RequestAdapterRequestRetrier自动为我的请求添加刷新令牌行为。 在没有控制的情况下无限期地重试的问题。 我有这段代码:

class AuthHandler: RequestAdapter, RequestRetrier {

    func adapt(_ urlRequest: URLRequest) throws -> URLRequest {

        return urlRequest

    }

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

        if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 {

            _ = Credential.current.renew({ (credential, error) in
                completion(true, 0.0) /// Retry request
            })

        } else {

            completion(false, 0.0) // Don't retry

        }

    }

}

如何在失败后只执行一次请求重试?

我试过了:

request.retryCount = 1

但不起作用......有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:4)

retryCount是只读的。 retryCount的说明是:

  

重试请求的次数。

因此,您需要做的就是检查此重试次数,并在retryCount过高时停止重试。

要在一次重试后停止,此代码将起作用:

class AuthHandler: RequestAdapter, RequestRetrier {

    func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
        return urlRequest
    }

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

        guard request.retryCount == 0 else { return completion(false, 0) } // relevant change

        if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 {

            _ = Credential.current.renew({ (credential, error) in
                completion(true, 0) /// Retry request
            })

        } else {
            completion(false, 0.0) // Don't retry
        }
    }
}

注意:第一次重试请求时,其retryCount为0.在上面的代码中,我们确保它仅在第一次重试时进行,其中retryCount == 0