diff Simoleon/Jobs/FileController.swift @ 154:8afba86ab8dd

Refactor code
author Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com>
date Wed, 25 Aug 2021 10:43:12 +0100
parents
children 681f2cbe8c7f
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Simoleon/Jobs/FileController.swift	Wed Aug 25 10:43:12 2021 +0100
@@ -0,0 +1,44 @@
+//
+//  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 JsonErrors.fileMissing
+        }
+        
+        do {
+            data = try Data(contentsOf: file)
+        } catch {
+            throw JsonErrors.loadFailed(cause: error.localizedDescription)
+        }
+        
+        do {
+            let decoder = JSONDecoder()
+            return try decoder.decode(T.self, from: data)
+        } catch {
+            throw JsonErrors.parseFailed(cause: error.localizedDescription)
+        }
+    }
+}