comparison Simoleon/Helpers/NetworkHelper.swift @ 156:84137052813d

Refactor code
author Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com>
date Sat, 28 Aug 2021 11:15:25 +0100
parents
children 0c589138a6f3
comparison
equal deleted inserted replaced
155:681f2cbe8c7f 156:84137052813d
1 //
2 // Request.swift
3 // Simoleon
4 //
5 // Created by Dennis Concepción Martín on 20/07/2021.
6 //
7
8 import Foundation
9
10 // MARK: - HTTP Request
11 func httpRequest<T: Decodable>(url: String, model: T.Type, completion: @escaping (_ result: T) -> Void) {
12
13 // We take some model data T.Type
14 guard let url = URL(string: url) else {
15 print("Invalid URL")
16 return
17 }
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 }