ios - 在 Swift 中获取子目录中资源的所有 URL

标签 ios swift xcode nsfilemanager subdirectory

我正在尝试为我的 iOS 应用程序的子目录中的所有资源创建一个 URL 数组。我似乎无法找到正确的路径,我希望即使不知道名称也能检索 URL(即我不想将文件名硬编码到代码中)。

下面是层次结构的屏幕截图,我试图获取“测试”文件夹中的所有文件: enter image description here

非常感谢任何帮助,我尝试使用文件管理器和 bundle 主路径,但到目前为止还没有成功。

这是我目前唯一的代码:

let fileManager = FileManager.default
let path = Bundle.main.urls(forResourcesWithExtension: "pdf", subdirectory: "Files/test")

print(path)

我也试过这段代码,但是它打印了所有资源,我似乎无法指定子目录:

let fm = FileManager.default
let path = Bundle.main.resourcePath!

do {
    let items = try fm.contentsOfDirectory(atPath: path)

    for item in items {
        print("Found \(item)")
    }
} catch {
    // failed to read directory – bad permissions, perhaps?
}

根据@vadian 的回答,文件夹已从虚拟组更改为真实文件夹。使用以下代码,我能够获得资源列表:

let fileManager = FileManager.default
    let path = Bundle.main.resourcePath

    let enumerator:FileManager.DirectoryEnumerator = fileManager.enumerator(atPath: "\(path!)/Files/test")!
    while let element = enumerator.nextObject() as? String {
        if element.hasSuffix("pdf") || element.hasSuffix("jpg") { // checks the extension
            print(element)
        }
    }

最佳答案

考虑黄色文件夹 enter image description here是虚拟,而不是真实文件夹(尽管 Xcode 在项目目录中创建真实文件夹)。构建应用程序时,黄色文件夹中的所有文件都将移动到 bundle 中的 Resources 目录中。

bundle 中的真实文件夹是 enter image description here在项目导航器中。

关于ios - 在 Swift 中获取子目录中资源的所有 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50004553/

相关文章:

ios - 我需要提交以供 Facebook 应用审查吗?

iphone - 如何按值对 plist 进行排序

ios - 使用 ReactiveCocoa 将 UIKit 与 View 模型绑定(bind) 3/4

ios - 如何更改 Objective-C 中的 CBAdvertisementDataLocalNameKey 值?

iOS - NSOperation 中的异步 NSURLConnection

ios - 将内容适配到 iPhone 屏幕

ios - TextField 变得崩溃

swift - 从 PhysicsBody 移除弹跳?

iphone - 在 Xcode 中找不到 CFNetwork

iphone - 本地通知