Last active
June 30, 2022 18:31
-
-
Save andresr-dev/c64eba9a5ce1387fea8e3cafc5fcc83f to your computer and use it in GitHub Desktop.
This is a bundle extension that helps you find a file previously saved in your app bundle and decode it from JSON format into any custom type you want, as long as it conforms to decodable protocol
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Astronaut: Codable, Identifiable { | |
let id: String | |
let name: String | |
let description: String | |
static let allAstronauts = Bundle.main.decode([Astronaut].self, from: "astronauts.json") | |
static let example = allAstronauts[0] | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Bundle { | |
func decode<T: Decodable>(_ type: T.Type, from file: String, dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) -> T { | |
guard let url = self.url(forResource: file, withExtension: nil) else { | |
fatalError("Failed to locate \(file) in bundle.") | |
} | |
guard let data = try? Data(contentsOf: url) else { | |
fatalError("Failed to load \(file) from bundle.") | |
} | |
let decoder = JSONDecoder() | |
decoder.dateDecodingStrategy = dateDecodingStrategy | |
decoder.keyDecodingStrategy = keyDecodingStrategy | |
do { | |
return try decoder.decode(T.self, from: data) | |
} catch DecodingError.keyNotFound(let key, let context) { | |
fatalError("Failed to decode \(file) from bundle due to missing key '\(key.stringValue)' - \(context.debugDescription)") | |
} catch DecodingError.typeMismatch(_, let context) { | |
fatalError("Failed to decode \(file) from bundle due to type missmatch - \(context.debugDescription)") | |
} catch DecodingError.valueNotFound(let type, let context) { | |
fatalError("Failed to decode \(file) from bundle due to missing \(type) value - \(context.debugDescription)") | |
} catch DecodingError.dataCorrupted(_) { | |
fatalError("Failed to decode \(file) from bundle because it appears to be invalid JSON.") | |
} catch { | |
fatalError("Failed to decode \(file) from bundle: \(error.localizedDescription)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment