简体   繁体   English

拖放到Xcode - Xcode / Swift后无法读取JSON文件

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

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". 我有一个名为recipes.json的json文件,我拖放到我的项目中,然后检查了“如果需要复制项目”。 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. 该应用程序在let data = try行崩溃。 The previous line outputs nil. 前一行输出为零。 Apparently the file doesn't exist even tho I copied it to the Xcode project. 显然,即使我将文件复制到Xcode项目,该文件也不存在。 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. 编辑:相同的代码在Playground中运行良好。 I had to use let fileURL = PlaygroundSupport.playgroundSharedDataDirectory.appendingPathComponent(jsonFile) after putting the file into the shared Playgrounds documents folder. 将文件放入共享的Playgrounds文档文件夹后,我不得不使用let fileURL = PlaygroundSupport.playgroundSharedDataDirectory.appendingPathComponent(jsonFile)

2 things to check. 要检查的2件事。

  1. Does jsonFile actually contain the correct name? jsonFile实际上是否包含正确的名称? It should be "recipes" . 它应该是"recipes"
  2. Did you add the JSON file to your target? 您是否将JSON文件添加到目标中? If you go to Build Phases it should show up in Copy Bundle Resources. 如果你去Build Phases,它应该出现在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. 如果没有,检查它应该将它添加到Copy Bundle Resources。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM