Thread 1: Fatal error: Couldn't find WeatherData.json in main bundle."

Hey guys, it has been a long time since I have posted :slight_smile: . My Weather app is showing me this error, and I have no idea what’s wrong. I even cleared the build folder, but still no progress. Can you help? I have the projekt linked below.

Thanks,
Harri

The solution was to:

  • copy out the WeatherData.json file from your project using Finder.
  • Delete the file within Xcode.
  • Drag the file back into Xcode making sure that “Copy items if needed” is checked and that “Add to targets” is also set.

I suspect that something was not quite right in the first place when it was initially added.

Something else that you might want to take on board is that your ModelData file contains a global variable previewWeather and a global function load().

Probably not a good practices to have global variables and functions so consider this alternative where the two are inside a struct and previewWeather becomes a computed property.

struct ModelData {

    var previewWeather: ResponseBody {
        load("WeatherData.json")
    }

    func load<T: Decodable>(_ filename: String) -> T {
        let data: Data

        guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
        else {
            fatalError("Couldn't find \(filename) in main bundle.")
        }

        do {
            data = try Data(contentsOf: file)
        } catch {
            fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
        }

        do {
            let decoder = JSONDecoder()
            return try decoder.decode(T.self, from: data)
        } catch {
            fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
        }
    }
}

Wherever you have used previewWeather in your code, you would need to change that to:

ModelData().previewWeather