3

我正在采用RequestAdapter并将RequestRetrier刷新令牌行为自动添加到我的请求中。重试的问题无限期地发生而不受控制。我有这个代码:

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

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

谢谢!

4

1 回答 1

6

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.

于 2017-05-19T17:35:04.330 回答