title: Problem making API request with async / await in swift 5.5
body: <p>I have a problem when I want to refactor my API requests to the new async / await functionality in swift 5.5.</p>
  <p>My code is (I remove all credentials and personal information, but the logic is the same):</p>
  <pre><code>class API {
      enum HTTPMethods: String {
          case GET = &quot;GET&quot;
          case POST = &quot;POST&quot;
      }
      
      // Credentials
      private let testKey = &quot;abcdef&quot;
      private var authenticationHeaders: [String: String] = [&quot;username&quot;: &quot;myUsername&quot;,
                                                             &quot;password&quot;: &quot;myPassword&quot;]
      private var token: String = &quot;MyToken&quot;
      
      // Data collected from the API requests
      private var a: Response1?
      private var b: Response2?
      
      // Base URLs
      private var url = &quot;https://example.com&quot;
      
      // Singleton
      static let singleton = API()
      private init() {
          // Increasing the interval for the timeout
          URLSession.shared.configuration.timeoutIntervalForRequest = 530.0
          URLSession.shared.configuration.timeoutIntervalForResource = 560.0
      }
      
      private func getRequest(url: URL, method: HTTPMethods) -&gt; URLRequest{
          var request = URLRequest(url: url)
          request.httpMethod = method.rawValue
          request.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)
          request.setValue(&quot;Token \(token)&quot;, forHTTPHeaderField: &quot;Authorization&quot;)
          return request
      }
      
      private func checkResponse(response: URLResponse?, nameRequest: String){
          if let httpResponse = response as? HTTPURLResponse {
              switch httpResponse.statusCode {
              case 200...201:
                  print(&quot;URL request made successfully!&quot;)
              default:
                  fatalError(&quot;Error in the request \(nameRequest), status code \(httpResponse.statusCode), response: \(String(describing: response))&quot;)
              }
          }
      }
      
      func makeAuthorization() async {
          let url = URL(string: url)!
          var request = getRequest(url: url, method: HTTPMethods.POST)
          // Insert json data to the request
          if let jsonData = try? JSONSerialization.data(withJSONObject: authenticationHeaders) {
              request.httpBody = jsonData
          }
          do {
              let (data, response) = try await URLSession.shared.data(for: request)
              if let response = try? JSONDecoder().decode(Response1.self, from: data) {
                  token = response.token
              }
              checkResponse(response: response, nameRequest: &quot;Authorization&quot;)
          } catch {
              fatalError(&quot;Request failed with error: \(error)&quot;)
          }
      }
      
      func getTestConfiguration() async {
          let url = URL(string: url)!
          let request = getRequest(url: url, method: HTTPMethods.GET)
          do {
              let (data, response) = try await URLSession.shared.data(for: request)
              if let response = try? JSONDecoder().decode(Response2.self, from: data) {
                  self.b = response
              }
              checkResponse(response: response, nameRequest: &quot;getTestConfiguration&quot;)
          } catch {
              fatalError(&quot;Request failed with error: \(error)&quot;)
          }
      }
      
  }
  
  
  struct Response1: Codable {
      let token: String
  }
  
  
  struct Response2: Codable {
      let token: String
  }
  </code></pre>
  <p>The code I am trying to refactor, the original in the old way, is:</p>
  <pre><code>func makeAuthorizationO() {
          if let urlObject = URL(string: url) {
              var request = getRequest(url: urlObject, method: HTTPMethods.POST)
              
              // Insert json data to the request
              if let jsonData = try? JSONSerialization.data(withJSONObject: authenticationHeaders) {
                  request.httpBody = jsonData
              }
              
              URLSession.shared.dataTask(with: request) { [self] data, response, error in
                  guard error == nil,
                        let _ = data else {
                            print(error ?? &quot;Error in makeAuthorization, but error is nil&quot;)
                            return
                        }
                  if let unwrappedData = data {
                      if let response = try? JSONDecoder().decode(Response1.self, from: unwrappedData) {
                          token = response.token
                          print(&quot;makeAuthorization successful!&quot;)
                      }
                  }
                  checkResponse(response: response, nameRequest: &quot;Authorization&quot;)
              }.resume()
          }
      }
      
      func getTestConfigurationO(){
          if let urlObject = URL(string: url) {
              URLSession.shared.dataTask(with: getRequest(url: urlObject, method: HTTPMethods.GET)) { data, response, error in
                  guard error == nil,
                        let _ = data else {
                            print(error ?? &quot;Error in getTestConfiguration, but error is nil&quot;)
                            return
                        }
                  if let unwrappedData = data {
                      let decoder = JSONDecoder()
                      if let test = try? decoder.decode(Response2.self, from: unwrappedData) {
                          self.b = test
                      }
                  }
                  self.checkResponse(response: response, nameRequest: &quot;TestConfiguration&quot;)
              }.resume()
          }
      }
  </code></pre>
  <p>The problem is, that with the new code, I have this error:</p>
  <pre><code>Error Domain=NSURLErrorDomain Code=-999 &quot;cancelled&quot; UserInfo={NSErrorFailingURLStringKey=https://example.com, NSErrorFailingURLKey=https://example.com, _NSURLErrorRelatedURLSessionTaskErrorKey=(
      &quot;LocalDataTask &lt;3B064821-156C-481C-8A72-30BBDEE5218F&gt;.&lt;3&gt;&quot;
  </code></pre>
  <p>I have absolutely no clue what is happening here, and to be more confused, the error is not happening always, most of the times, but sometimes the code executes correctly. What is the problem for this behaviour and this error? PD: the original code, before changing to async / await works absolutely fine always</p>
  <p>The way I call the method, is on the appear of the main view:</p>
  <pre><code>struct MyView: View {
      var body: some View {
          VStack {
              Text(&quot;My message&quot;)
          }.task {
              let api = API.singleton
              await api.makeAuthorization()
              await api.getTestConfiguration()
          }
      }
  }
  </code></pre>