Skip to content

Instantly share code, notes, and snippets.

@rahul-inspired-iosdeveloper
Last active March 3, 2020 18:31
Show Gist options
  • Save rahul-inspired-iosdeveloper/20cf64a74a53ee969282c6f0edd6c87c to your computer and use it in GitHub Desktop.
Save rahul-inspired-iosdeveloper/20cf64a74a53ee969282c6f0edd6c87c to your computer and use it in GitHub Desktop.
import Foundation
struct BaseURL {
static let baseURL = "https://learnappmaking.com/"
}
struct AppAPI {
static let usersListAPI = "ex/users.json"
}
class NetworkClient {
//MARK:- Properties
var defaultSession: URLSession?
var dataTask: URLSessionDataTask?
var request: URLRequest?
//MARK:- Initialiser
required init() {
defaultSession = URLSession(configuration: .default)
}
//MARK:- Shared Instance
static let shared = NetworkClient()
}
extension NetworkClient {
//MARK:- Custom Accessors
func fetchData(completion:@escaping(_ users:[User]?)->()) {
let url = URL(string: BaseURL.baseURL+AppAPI.usersListAPI)
request = URLRequest(url: url!)
request?.httpMethod = "GET"
dataTask = defaultSession?.dataTask(with: request!) { data, response, error in
guard error == nil && data != nil else {
return
}
if let data = data {
let decoder = JSONDecoder()
do {
let userResponse = try decoder.decode(UserResponse.self, from: data)
completion(userResponse)
} catch {
print("JSON error: \(error.localizedDescription)")
}
}
}
dataTask?.resume()
}
}
//MARK:- User
struct User: Codable {
let firstName, lastName: String
let age: Int
enum CodingKeys: String, CodingKey {
case firstName = "first_name"
case lastName = "last_name"
case age
}
}
typealias UserResponse = [User]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment