Mercurial > public > simoleon
diff Simoleon/Helpers/NetworkHelper.swift @ 160:0c589138a6f3
Implement Conversion Box
author | Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com> |
---|---|
date | Sun, 29 Aug 2021 19:04:34 +0100 |
parents | 84137052813d |
children |
line wrap: on
line diff
--- a/Simoleon/Helpers/NetworkHelper.swift Sat Aug 28 19:18:50 2021 +0100 +++ b/Simoleon/Helpers/NetworkHelper.swift Sun Aug 29 19:04:34 2021 +0100 @@ -7,32 +7,29 @@ import Foundation -// MARK: - HTTP Request -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 +class NetworkHelper { + func httpRequest<T: Decodable>(url: String, model: T.Type, completion: @escaping (_ result: T) -> Void) throws { + // We take some model data T.Type + guard let url = URL(string: url) else { throw ErrorHandling.Networking.invalidURL } + + 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() } - - 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() }