Skip to content

Instantly share code, notes, and snippets.

@black-dragon74
Created September 22, 2019 09:56
Show Gist options
  • Save black-dragon74/8d19ef8afe110ae6ba1f179f8a556704 to your computer and use it in GitHub Desktop.
Save black-dragon74/8d19ef8afe110ae6ba1f179f8a556704 to your computer and use it in GitHub Desktop.
A helper class to decode JSON data from a JSON file in the bundle or from a `Data` object instance. The class exposes two static functions that user can call without initializing the class.
//
// JSONLoader.swift
// Load JSON from file and data objects effortlessly
//
// Created by Nick on 9/22/19.
// Copyright © 2019 Nick. All rights reserved.
//
import Foundation
class JSONLoader: NSObject {
static func loadJSON<T: Codable>(from file: String) -> T {
// Get the file URL from the bundle
guard let fileURL = Bundle.main.url(forResource: file, withExtension: nil) else { fatalError("File not found at given path") }
// Do not worry about force cast, if it is empty, it will lead to a fala error below
var data: Data!
// Construct the data
do {
data = try Data(contentsOf: fileURL)
}
catch let ex {
fatalError("Unable to get data from the JSON file: \(ex.localizedDescription)")
}
// Decode the JSON else die
let decoder = JSONDecoder()
do {
return try decoder.decode(T.self, from: data)
}
catch let ex {
fatalError("Unable to decode the JSON data: \(ex.localizedDescription)")
}
}
static func decodeJSON<T: Codable>(from data: Data) -> T {
let decoder = JSONDecoder()
do {
return try decoder.decode(T.self, from: data)
}
catch let ex {
fatalError("Unable to decode from the JSON: \(ex.localizedDescription)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment