Can't read JSON file after dragging and dropping into Xcode - Xcode/Swift

Viewed 2727

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.

1 Answers
Related