Getting error " Thread 1: Fatal error: Could not decode sanantoniotx.json from bundle."
Here is my code.
// MARK: - Welcome
struct Welcome: Codable {
var status: String
var urgentAdsHTML, data: [AdInfo]
}
// MARK: - AdInfo
struct AdInfo: Codable {
var aid, bname, bcity: String?
var bstate: Bstate?
var distance: String?
var cangap: String?
var vip: Int?
var photo: [String: String]?
var adsTitle, adsMsg, status: String?
var urgentAdsHTML: [AdInfo]?
enum CodingKeys: String, CodingKey {
case aid, bname, bcity, bstate, distance, cangap, vip, photo
case adsTitle
case adsMsg
case status, urgentAdsHTML
}
static let allAds: [AdInfo] = Bundle.main.decode(file: "sanantoniotx.json")
static let sampleAd: AdInfo = allAds[0]
}
enum Bstate: String, Codable {
case tx = "TX"
}
extension Bundle {
func decode<T: Decodable>(file: String) -> T {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Could not find \(file) in bundle.")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Could not load \(file) from bundle.")
}
let decoder = JSONDecoder()
guard let loadedData = try? decoder.decode(T.self, from: data) else {
fatalError("Could not decode \(file) from bundle.")
}
return loadedData
}
}
receiving the error at.
fatalError("Could not decode \(file) from bundle.")
Id be very thankful if anyone can help.
Id be very thankful if anyone can help.
Actually nobody can really help yet, because the try?
in this line silently eats the thrown error:
guard let loadedData = try? decoder.decode(T.self, from: data) else {
You should move the decoding into a do
/ catch
block, and then you can examine the error that gets thrown. What does it say?