view Simoleon/Jobs/FileController.swift @ 155:681f2cbe8c7f

Refactor error handling class
author Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com>
date Wed, 25 Aug 2021 11:00:21 +0100
parents 8afba86ab8dd
children
line wrap: on
line source

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

import Foundation

class FileController {
    
    /*
     Read configuration variables from Config.xconfig
     */
    func readConfigVariable(withKey: String) -> String? {
        return (Bundle.main.infoDictionary?[withKey] as? String)?
            .replacingOccurrences(of: "\\", with: "")
    }
    
    /*
     Decode and read json file
     */
    func read<T: Decodable>(json filename: String) throws -> T {
        let data: Data
        
        guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
        else {
            throw ErrorHandling.Json.fileMissing
        }
        
        do {
            data = try Data(contentsOf: file)
        } catch {
            throw ErrorHandling.Json.loadFailed(cause: error.localizedDescription)
        }
        
        do {
            let decoder = JSONDecoder()
            return try decoder.decode(T.self, from: data)
        } catch {
            throw ErrorHandling.Json.parseFailed(cause: error.localizedDescription)
        }
    }
}