使用 Swift 读取 Xcode 项目中的文件

Read file in Xcode project with Swift

我做了一个从临时文件夹中读取文件的方法。我使用以下行来获取文档的路径:

path = NSTemporaryDirectory().stringByAppendingPathComponent(folder)
path = path.stringByAppendingPathComponent(fileName + "." + fileType)

而且效果很好。我的问题是:如何获取位于 Xcode 项目主文件夹中的文件的路径?它们是我从文件夹拖放到 Xcode 项目中的两个文本文件。我在删除文件时选择了 "copy files if needed" 选项。谢谢!

您将使用 NSBundle 获取主包,然后 pathForResource(_ name: String?, ofType extension: String?) -> String?

您要查找的是应用程序的主捆绑包。你得到一个文件的路径是这样的:

if let path = NSBundle.mainBundle().pathForResource(fileName, ofType:fileType) {
    // use path
}

请记住,此文件夹是只读的,因此如果要进行更改,您需要将文件复制到临时文件夹或文档文件夹。

更新 Swift 3.1 - 感谢@Filip Radelic

if let path = Bundle.main.path(forResource: fileName, ofType: fileType) {
    // use path
    print(path)
}

Swift 4

  if let path = Bundle.main.path(forResource: "imagename.png", ofType: nil) {
           print("[check] FILE AVAILABLE \(path)")
        }