comparison Simoleon/Functions/HttpRequest.swift @ 185:2fc95efcb1ee

connect backend
author Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com>
date Wed, 22 Dec 2021 16:12:23 +0100
parents
children
comparison
equal deleted inserted replaced
184:7cb2b0b2b3f3 185:2fc95efcb1ee
1 //
2 // HttpRequest.swift
3 // Simoleon
4 //
5 // Created by Dennis Concepción Martín on 21/12/21.
6 //
7
8 import Foundation
9
10 // Network request
11 func httpRequest<T: Decodable>(url: String, model: T.Type, completion: @escaping (_ result: T) -> Void) {
12 guard let url = URL(string: url) else {
13 print("Invalid URL")
14 return
15 }
16 let request = URLRequest(url: url)
17 URLSession.shared.dataTask(with: request) { data, response, error in
18 if let data = data {
19 do {
20 // Decode response with the model passed
21 let decodedResponse = try JSONDecoder().decode(model, from: data)
22 DispatchQueue.main.async {
23 completion(decodedResponse)
24 }
25 return
26 } catch {
27 // Return error regarding the escaping code
28 print(error)
29 }
30 }
31 // Error with the request
32 print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
33 }
34 .resume()
35 }