gpt4 book ai didi

swift - 从目录中读取所有文件?

转载 作者:搜寻专家 更新时间:2023-11-01 06:01:35 26 4
gpt4 key购买 nike

我正在尝试在我的 Assets 中创建一个文件夹,然后获取其中的文件列表。听起来很简单,但对于如何做到这一点并没有明确的答案。

  1. 即使是从主目录中获取列表,大多数人在 Swift 3 上也做不到,阅读这里:Getting list of files in documents folder

使用:

let fileMngr = FileManager.default;

// Full path to documents directory
let docs = fileMngr.urls(for: .documentDirectory, in: .userDomainMask)[0].path

// List all contents of directory and return as [String] OR nil if failed
return try? fileMngr.contentsOfDirectory(atPath:docs)

不工作。

  1. 从特定文件夹中读取,我不明白如何获取它的 swift 路径。

有没有真正有效的从文件夹中读取的示例?

最佳答案

如果你想获取个人目录中的所有文件,这里是简单的答案

    do {
let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let Path = documentURL.appendingPathComponent("yourDirectoyName").absoluteURL
let directoryContents = try FileManager.default.contentsOfDirectory(at: Path, includingPropertiesForKeys: nil, options: [])
}
catch {
print(error.localizedDescription)
}

然后如果你想读取所有具有特殊扩展名的文件,你可以这样做

static func listAllFileNamesExtension(nameDirectory: String, extensionWanted: String) -> (names : [String], paths : [URL]) {

let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let Path = documentURL.appendingPathComponent(nameDirectory).absoluteURL

do {
try FileManager.default.createDirectory(atPath: Path.relativePath, withIntermediateDirectories: true)
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory(at: Path, includingPropertiesForKeys: nil, options: [])

// if you want to filter the directory contents you can do like this:
let FilesPath = directoryContents.filter{ $0.pathExtension == extensionWanted }
let FileNames = FilesPath.map{ $0.deletingPathExtension().lastPathComponent }

return (names : FileNames, paths : FilesPath);

} catch {
print(error.localizedDescription)
}

return (names : [], paths : [])
}

所以如果你想把所有的json文件放在你的个人目录中

let allJsonNamePath = listAllFileNamesExtension(nameDirectory:"yourDirectoryName", extensionWanted: "json")

关于swift - 从目录中读取所有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48439292/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com