Swift - Build a HTTP client

27 Oct 2020

I use URLSession to do the HTTP request. We also need a HTTPClient class and a NetworkError enum.

import Foundation

struct User: Codable {
  let id: String
  let username: String
}

extension URL {
  static func forUserById(_ id: String) -> URL? {
    return URL(string: "https://example.com/users/\(id)")
  }
}

enum NetworkError: Error {
  case badURL
  case noData
  case decodingError
}

class HTTPClient {
  func getUserBy(id: String, completion: @escaping (Result<User, NetworkError>) -> Void) {
    guard let url = URL.forUserById(id) else {
      return completion(.failure(.badURL))
    }

    URLSession.shared.dataTask(with: url) { data, response, error in
      guard let data = data, error == nil else {
        return completion(.failure(.noData))
      }

      guard let user = try? JSONDecoder().decode(User.self, from: data) else {
        return completion(.failure(.decodingError))
      }

      completion(.success(user))
    }
  }
}
Back to top