Is there a way to do Alamofire requests with retries

后端 未结 4 1982
离开以前
离开以前 2020-12-15 09:09

I have a lot of places in the code where Alamofire request/response are handled.

Each of this requests may fail because of some intermittent problem (the most commo

4条回答
  •  有刺的猬
    2020-12-15 09:40

    Alamofire 4.0 has a RequestRetrier protocol you can use.

    https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md#request-retrier

    Example:

    class OAuth2Handler: RequestAdapter, RequestRetrier {
        public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: RequestRetryCompletion) {
            if let response = request.task.response as? HTTPURLResponse, response.statusCode == 401 {
                completion(true, 1.0) // retry after 1 second
            } else {
                completion(false, 0.0) // don't retry
            }
    
            // Or do something with the retryCount
            // i.e. completion(request.retryCount <= 10, 1.0)
        }
    }
    
    let sessionManager = SessionManager()
    sessionManager.retrier = OAuth2Handler()
    
    sessionManager.request(urlString).responseJSON { response in
        debugPrint(response)
    }
    

提交回复
热议问题