如何获取主包中子文件夹的路径?

How to get path to a subfolder in main bundle?

我有一个项目,我正在从 Obj-C 迁移到 Swift 3.0(我是 Swift 的菜鸟)。

如何翻译这行?

NSString *folder = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myfolder"];

我成功获取了资源路径:

let resoursePath = Bundle.main.resoursePath;

但是如何获取名为 "myfolder" 的子文件夹的路径? 我需要获取子文件夹的路径,而不是其中文件的路径。

在Swift-3中生成URL,然后调用appendingPathComponent:

let resourcePath = Bundle.main.resourcePath
let subdir = URL(fileURLWithPath:resourcePath!).appendingPathComponent("sub").path

或干脆

let subdir = Bundle.main.resourceURL!.appendingPathComponent("sub").path

(谢谢,Martin R!)

有关 Swift 中 stringByAppendingPathComponent 方法的信息,请参见

您可以使用此方法获取 bundle 子目录的列表并仅获取特定类型的资源:

Bundle.main.paths(forResourcesOfType: type, inDirectory: folder)

你可以这样做:

let folderURL = resourceURL(to: "myfolder")

func resourceURL(to path: String) -> URL? {
    return URL(string: path, relativeTo: Bundle.main.resourceURL)
}