I'm making a simple JSON loading function in my viewmodel, which retrieves the data from a localized JSON file. However, when I call the function it doesn't seem to find anything at all.
func loadJson() {
guard let url = Bundle.main.url(forResource: "parkson", withExtension: "json") /// For some reason, this can't find the url for the Json file
else {
print("ERROR - JSON FILE NOT FOUND")
print(Bundle.main.urls(forResourcesWithExtension: "json", subdirectory: "Model") ?? "There's nothing here...")
return
}
do {
let data = try Data(contentsOf: url)
let parkInfos = try JSONDecoder().decode([ParkInfo].self, from: data)
self.listOfParkInfo = parkInfos
} catch {
print("ERROR - FAILED TO LOAD JSON --- \(error.localizedDescription)")
}
}
(For reference, the name of the JSON file is parkson.json
)
When the function is called, it simply prints the "ERROR - JSON FILE NOT FOUND" from the print statement, but in the next print statement it's just "[]"
"ERROR - JSON FILE NOT FOUND" and "[]"
Not sure what I did wrong, most online tutorials use this same function.
Finder
and drag and drop the file into your Xcode project (left pannel).