获取 Swift 子目录中资源的所有 URL [英] Get all URLs for resources in sub-directory in Swift

查看:49
本文介绍了获取 Swift 子目录中资源的所有 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting to create an array of URLs for all of the resources in a sub-directory in my iOS app. I can not seem to get to the correct path, I want to be able to retrieve the URLs even if I do not know the names (i.e. I don't want to hard code the file names into the code).

下面是层次结构的屏幕截图,我试图获取test"文件夹中的所有文件:

Below is a screen shot of the hierarchy, I am attempting to get all the files in the 'test' folder:

非常感谢任何帮助,我尝试使用文件管理器和捆绑主路径,但到目前为止没有任何乐趣.

Any help is greatly appreciated, I have attempted to use file manager and bundle main path but to no joy so far.

这是我目前唯一的代码:

This is the only code I have currently:

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

print(path)

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

I have also tried this code but this prints all resources, I can't seem to specify a sub-directory:

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 的回答,文件夹已从虚拟组更改为真实文件夹.使用以下代码,我可以获得资源列表:

Based on an answer from @vadian , The folders were changed from virtual groups to real folders. Using the following code I was able to get a list of resources:

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)
        }
    }

推荐答案

考虑黄色文件夹 是虚拟的,不是真正的文件夹(尽管 Xcode在项目目录中创建真正的文件夹).构建应用程序时,黄色文件夹中的所有文件都会移动到包中的 Resources 目录中.

Consider that the yellow folders are virtual groups, not real folders (although Xcode creates real folders in the project directory). All files in the yellow folders are moved into the Resources directory in the bundle when the app is built.

捆绑包中的真实文件夹是 在项目导航器中.

Real folders in the bundle are in the project navigator.

这篇关于获取 Swift 子目录中资源的所有 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆