I can't believe I've been stuck in such a supposed to be easy task.
I have a json file called recipes.json that I dragged and dropped into my project and I checked "Copy items if needed". However I can't access it no matter what.
func parseRecipesJSON(jsonFile: String) -> [RecipeItem] {
var recipesArray = [RecipeItem]()
do {
let jsonFile = Bundle.main.url(forResource: jsonFile, withExtension: "json")
print("## ", jsonFile as Any)
let data = try Data(contentsOf: jsonFile!)
let json = try JSONSerialization.jsonObject(with: data, options: [])
// my code
} catch {
print(error)
}
return recipesArray
}
The app crashes at the let data = try line. The previous line outputs nil. Apparently the file doesn't exist even tho I copied it to the Xcode project. I couldn't find it in the simulator's files either. What am I doing wrong here?
EDIT: The same code worked fine in Playground.
I had to use let fileURL = PlaygroundSupport.playgroundSharedDataDirectory.appendingPathComponent(jsonFile)
after putting the file into the shared Playgrounds documents folder.
2 things to check.
jsonFile
actually contain the correct name? It should be "recipes"
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With