comparison 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
comparison
equal deleted inserted replaced
153:2590ee472aa9 154:8afba86ab8dd
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 class NetworkController {
11
12 /*
13 Get http response and decode it with specified model
14 */
15 func httpRequest<T: Decodable>(url: String, model: T.Type, completion: @escaping (_ result: T) -> Void) {
16
17 // We take some model data T.Type
18 guard let url = URL(string: url) else {
19 print("Invalid URL")
20 return
21 }
22
23 let request = URLRequest(url: url)
24 URLSession.shared.dataTask(with: request) { data, response, error in
25 if let data = data {
26 do {
27 // Decode response with the model passed
28 let decodedResponse = try JSONDecoder().decode(model, from: data)
29 DispatchQueue.main.async {
30 completion(decodedResponse)
31 }
32 return
33 } catch {
34 // Return error regarding the escaping code
35 print(error)
36 }
37 }
38 // Error with the request
39 print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
40 }
41 .resume()
42 }
43 }