加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:46:26 所属栏目:百科 来源:网络整理
导读:使用时 let directoryEnumerator = FileManager().enumerator(at: ... 在Swift 3中,我从文件夹中获取所有文件,例如 "file:///Volumes/MacOS/fasttemp/Fotos/" 结果不包括前导路径(此处为“/ Volumes / MacOS”).所以我明白了 "file:///fasttemp/Fotos/2005/"
使用时
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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读