Pet*_*r71 2 file path enumerator swift
使用时
let directoryEnumerator = FileManager().enumerator(at: ...
Run Code Online (Sandbox Code Playgroud)
在 Swift 3 中,我从文件夹中获取所有文件,例如
"file:///Volumes/MacOS/fasttemp/Fotos/"
Run Code Online (Sandbox Code Playgroud)
结果不包括主要路径(此处为“/Volumes/MacOS”)。所以我得到
"file:///fasttemp/Fotos/2005/"
Run Code Online (Sandbox Code Playgroud)
如何获取完整路径(直接从枚举器)或转换它们。我想使用 URL 函数,而不是通过假设进行操作的字符串函数。
如果“MacOS”是当前启动磁盘的名称,则“/Volumes/MacOS”是“/”的符号链接,因此“/fasttemp/Fotos/2005/”和“/Volumes/MacOS/fasttemp/Fotos/” " 是同一文件的绝对路径。
为了获得唯一的文件名表示形式,您可以查询 URL 以获取其规范路径。例子:
let url = URL(fileURLWithPath: "/Volumes/MacOS/Applications/Utilities/")
if let cp = (try? url.resourceValues(forKeys: [.canonicalPathKey]))?.canonicalPath {
print(cp)
}
// Output: "/Applications/Utilities"
Run Code Online (Sandbox Code Playgroud)
这需要 macOS 10.12/iOS 10 或更高版本。在旧系统上,您可以使用realpath()系统调用:
if let rp = url.withUnsafeFileSystemRepresentation ({ realpath($0, nil) }) {
let fullUrl = URL(fileURLWithFileSystemRepresentation: rp, isDirectory: true, relativeTo: nil)
free(rp)
print(fullUrl.path)
}
// Output: "/Applications/Utilities"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3293 次 |
| 最近记录: |