Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

xcode

ios

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.

like image 994
Tarek Avatar asked Sep 15 '17 17:09

Tarek


1 Answers

2 things to check.

  1. Does jsonFile actually contain the correct name? It should be "recipes".
  2. Did you add the JSON file to your target? If you go to Build Phases it should show up in Copy Bundle Resources. Since it's a resource file, if you select it and look at the File inspector, at the Target Membership list, the target in question should show up as checked. If not, checking it should add it to Copy Bundle Resources.
like image 172
Lily Ballard Avatar answered Nov 14 '22 23:11

Lily Ballard