Alamofire auto refresh token and retry previous API call in iOS Swift 4

前端 未结 2 462
耶瑟儿~
耶瑟儿~ 2021-02-04 21:58

now I\'m working on an iOS application in Swift 4. Here I\'m using Alamofire to integrate the API calls. I need to integrate the right way to auto-refresh the authentication tok

2条回答
  •  孤城傲影
    2021-02-04 22:26

    @m1sh0's answer was extremely helpful to me. I'm just adding the missing detail the OP asked for in the comments: How do you make the Alamofire request so that it uses the Retrier and Adapter?

    I basically used @m1sh0's example and called it like this:

            var request_url = Constants.API_URL + "/path/to/resource"
    
            let sessionManager = Alamofire.SessionManager.default
            sessionManager.adapter = MyRequestAdapter.shared
            
            sessionManager.request(request_url).validate().responseJSON { (response: DataResponse) in
                switch(response.result) {
                case .success(_):
                    print(response.result.value!)
                    completion(response.result.value!)
                case .failure(_):
                    print(response.result.error!)
                    completion(response.result.error!)
                    break
                }
            }
    

    Note that you need validate() in the request in order to get retried on failure. Without it, the response is just returned for completion. Also note there's a failure case in the response block for all non-401 errors, as they are presumed unrecoverable.

提交回复
热议问题