comparison 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
comparison
equal deleted inserted replaced
159:35628bac01f5 160:0c589138a6f3
5 // Created by Dennis Concepción Martín on 20/07/2021. 5 // Created by Dennis Concepción Martín on 20/07/2021.
6 // 6 //
7 7
8 import Foundation 8 import Foundation
9 9
10 // MARK: - HTTP Request 10 class NetworkHelper {
11 func httpRequest<T: Decodable>(url: String, model: T.Type, completion: @escaping (_ result: T) -> Void) { 11 func httpRequest<T: Decodable>(url: String, model: T.Type, completion: @escaping (_ result: T) -> Void) throws {
12 12 // We take some model data T.Type
13 // We take some model data T.Type 13 guard let url = URL(string: url) else { throw ErrorHandling.Networking.invalidURL }
14 guard let url = URL(string: url) else { 14
15 print("Invalid URL") 15 let request = URLRequest(url: url)
16 return 16 URLSession.shared.dataTask(with: request) { data, response, error in
17 if let data = data {
18 do {
19 // Decode response with the model passed
20 let decodedResponse = try JSONDecoder().decode(model, from: data)
21 DispatchQueue.main.async {
22 completion(decodedResponse)
23 }
24 return
25 } catch {
26 // Return error regarding the escaping code
27 print(error)
28 }
29 }
30 // Error with the request
31 print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
32 }
33 .resume()
17 } 34 }
18
19 let request = URLRequest(url: url)
20 URLSession.shared.dataTask(with: request) { data, response, error in
21 if let data = data {
22 do {
23 // Decode response with the model passed
24 let decodedResponse = try JSONDecoder().decode(model, from: data)
25 DispatchQueue.main.async {
26 completion(decodedResponse)
27 }
28 return
29 } catch {
30 // Return error regarding the escaping code
31 print(error)
32 }
33 }
34 // Error with the request
35 print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
36 }
37 .resume()
38 } 35 }