使用时
let directoryEnumerator = FileManager().enumerator(at: ...
在 Swift 3 中,我从文件夹中获取所有文件,例如
"file:///Volumes/MacOS/fasttemp/Fotos/"
结果不包括前导路径(此处为“/Volumes/MacOS”)。所以我得到
"file:///fasttemp/Fotos/2005/"
如何获取完整路径(直接从枚举器获取)或转换它们。我想使用 URL 函数,而不是通过假设操作的字符串函数。
最佳答案
如果“MacOS”是您当前启动盘的名称,那么“/Volumes/MacOS”是“/”的符号链接(symbolic link),因此“/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"
这需要 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"
关于swift - 获取完整路径或转换为完整路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40397131/