I am getting this error:
Moonshot/Bundle-Decodable.swift:24: Fatal error: Failed to decode missions.json from bundle.
2022-12-14 16:32:30.116683-0800 Moonshot[32049:1148957] Moonshot/Bundle-Decodable.swift:24: Fatal error: Failed to decode missions.json from bundle.
(lldb)
This is after getting to about 5:00 into : https://www.youtube.com/watch?v=kD8nolPczTc where we first setup the view.
I compared my Mission.swift
/ Bundle-Decodable.swift
/ and other files to the github code but didnt see anything obvious.
I am guessing that since it is getting the url and loading the data there is some error in my Mission struct? or Bundle-Decodable file. But am not really sure how to track this down.
Is there a way I can view this error in more detail to see what is causing a decoding error?
Thanks.
//Mission.swift
import Foundation
struct Mission: Codable, Identifiable {
struct CrewRole: Codable {
let name: String
let roll: String
}
let id: Int
let launchDate: String?
let crew: [CrewRole]
let description: String
var displayName: String {
"Apollo \(id)"
}
var image: String {
"apollo\(id)"
}
}
//Bundle-Decodable.swift
import Foundation
extension Bundle {
func decode<T: Codable>(_ file: String) -> 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()
guard let loaded = try? decoder.decode(T.self, from: data) else {
fatalError("Failed to decode \(file) from bundle.")
}
return loaded
}
}
//ContentView.swift
import SwiftUI
struct ContentView: View {
let astronauts: [String: Astronaut] = Bundle.main.decode("astronauts.json")
let missions: [Mission] = Bundle.main.decode("missions.json")
let columns = [
GridItem(.adaptive(minimum: 150))
]
var body: some View {
NavigationView {
ScrollView {
LazyVGrid(columns: columns ) {
ForEach(missions) { mission in
NavigationLink {
Text("Detail view")
} label: {
VStack {
Image(mission.image)
.resizable()
.scaledToFit()
.frame(width: 100, height: 100)
VStack {
Text(mission.displayName)
.font(.headline)
Text(mission.launchDate ?? "N/A")
.font(.caption)
}
.frame(maxWidth: .infinity)
}
}
}
}
}
.navigationTitle("Moonshot")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}