view 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
line wrap: on
line source

//
//  Request.swift
//  Simoleon
//
//  Created by Dennis Concepción Martín on 20/07/2021.
//

import Foundation

class NetworkController {
    
    /*
     Get http response and decode it with specified model
     */
    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
        }
        
        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()
    }
}