无法访问加载到项目中的文件

trouble accessing files loaded into project

我已将一堆文件添加到我的 swift 项目文件夹中,如下所示:

出于两个目的,我需要在项目中的某个点访问这些文件:

  1. 使用每个文件的名称来填充类别(即年龄、孤独、惊人...)
  2. 访问文件中的数据以填充每个类别项目页面

我已经在我的 class 的 viewDidLoad 中实现了这段代码来访问和遍历文件

//get categories
let fileManager = NSFileManager.defaultManager()
let directoryPath = NSHomeDirectory() + "/Categories"
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(directoryPath)!

while let element = enumerator.nextObject() as? String {
  println(String(element))
}

这不起作用并在行 let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(directoryPath)! 上产生错误 fatal error: unexpectedly found nil while unwrapping an Optional value。我怀疑(如果我错了请纠正我),它正在访问应用程序内部文件结构,因此找不到指定的文件。由于我是 IOS 开发的新手,我对它的工作原理的一般理解充其量是模糊的。

所以 我究竟该如何访问我按照图像中显示的方式添加项目的文件,以便遍历并获取我正在寻找的数据

编辑

所以我更改了结构,使 Categories 文件夹成为一个实际的文件夹,如下所示:

我目前正在尝试使用 NSBundle 访问应用程序路由,但我不确定如何操作。任何指导将不胜感激。

问题是 xcode 的项目导航器文件夹不是磁盘中的实际文件夹。所以这个:

let directoryPath = NSHomeDirectory() + "/Categories"

您的硬盘中不存在。如果你想要这个文件夹,你必须导航到硬盘上的项目文件夹,手动创建它并在其中添加你想要的文件。

你可以参考一个文件,这样读:

let htmFile = NSBundle.mainBundle().pathForResource("aboutText", ofType: "html")
let htmlString = NSString(contentsOfFile: htmFile!, encoding: NSUTF8StringEncoding, error: nil)

对于 json 你可以用

得到一本字典
let jsonFile = NSBundle.mainBundle().pathForResource("aboutText", ofType: "json")
let dict = NSDictionary(contentsOfFile: jsonFile)