[英]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件事。
jsonFile
actually contain the correct name? jsonFile
实际上是否包含正确的名称? It should be "recipes"
. 它应该是"recipes"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.