title: Using refresh token to get new authorization token and repeat failed api call
body: <p>I have a general question about using tokens in swift to make api calls. The authorization token that is needed to make api calls expires every hour so I need a way to handle this in a generalized way for multiple api calls. </p>
  
  <p>I'm facing an issue where if I get a 401 error I call a function to use the refresh token to get a new authorization token and I would like to re call the original function that gotten 401 error.</p>
  
  <p>For example:</p>
  
  <p>If I get a 401 error when I call <code>getDetails()</code> I want to call the <code>getNewAuthToken()</code> and after I get a new refresh token I want to call  <code>getDetails()</code> again. </p>
  
  <p>I want to do this in a way so that if I call any function <code>getX()</code> and I get a 401 error it calls <code>getNewAuthToken()</code> and then it calls the original function again  <code>getX()</code></p>
  
  <p>What would be the best way to approach this without using any external libraries etc. Would the best way be using a sort of callback function ?</p>
  
  <p>I have provided general code I've been implementing but as you can see when I get a 401 error it calls the <code>getNewAuthToken()</code> function but the original function is not called again. How can this code be modified to behave as needed?</p>
  
  <pre><code>import UIKit
  import Combine
  
  @Published var details: Details = nil
  
  func getNewAuthToken(){
  // here I request a token using the refresh token
  
  }
  
  func getDetails(){
      self.getCurrentDetails{ details in
          DispatchQueue.main.async {
               self.details = details
          }
      }
  }
  
  func getCurrentDetails(_ completionHandler: @escaping (Details) -&gt; ()) {
      let url = "https://api.xxx.com/details"
      guard let detailsURL = URL(string: url) else{
          fatalError("URL not valid")
      }
      let authtoken = keychain.get("authtoken") ?? ""
      var request = URLRequest(url: detailsURL)
      request.httpMethod = "GET"
      request.addValue("Bearer \(authtoken)", forHTTPHeaderField: "Authorization")
      let session = URLSession.shared
  
      let task = session.dataTask(with: request){
          data, response, error in
          let httpResponse = response as? HTTPURLResponse
          // I request a new token
          if(httpResponse?.statusCode == 401){
              print("401")
              self.getNewAuthToken()
              return
          }
          do {
              if(httpResponse?.statusCode != 200){
                  return
              }
              let decoder = JSONDecoder()
              let details = try decoder.decode(Details.self, from:
                  data!)
              completionHandler(details)
  
          } catch  let error2{
              print(error2)
          }
      }
      task.resume()
  }
  </code></pre>