swift – 获取完整路径或转换为完整路径

使用时
let directoryEnumerator = FileManager().enumerator(at: ...

在Swift 3中,我从文件夹中获取所有文件,例如

"file:///Volumes/MacOS/fasttemp/Fotos/"

结果不包括前导路径(此处为“/ Volumes / MacOS”).所以我明白了

"file:///fasttemp/Fotos/2005/"

如何获取完整路径(直接来自枚举器)或转换它们.我想使用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"

这需要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"

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...