Mercurial > public > simoleon
diff Simoleon/Jobs/NetworkController.swift @ 154:8afba86ab8dd
Refactor code
author | Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com> |
---|---|
date | Wed, 25 Aug 2021 10:43:12 +0100 |
parents | |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Simoleon/Jobs/NetworkController.swift Wed Aug 25 10:43:12 2021 +0100 @@ -0,0 +1,43 @@ +// +// Request.swift +// Simoleon +// +// Created by Dennis Concepción Martín on 20/07/2021. +// + +import Foundation + +class NetworkController { + + /* + Get http response and decode it with specified model + */ + func httpRequest<T: Decodable>(url: String, model: T.Type, completion: @escaping (_ result: T) -> Void) { + + // We take some model data T.Type + guard let url = URL(string: url) else { + print("Invalid URL") + return + } + + let request = URLRequest(url: url) + URLSession.shared.dataTask(with: request) { data, response, error in + if let data = data { + do { + // Decode response with the model passed + let decodedResponse = try JSONDecoder().decode(model, from: data) + DispatchQueue.main.async { + completion(decodedResponse) + } + return + } catch { + // Return error regarding the escaping code + print(error) + } + } + // Error with the request + print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")") + } + .resume() + } +}