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

标签 swift file path enumerator

使用时

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/

相关文章:

swift - GMSMarker 渲染和滞后问题

objective-c - 以编程方式唤醒 OSX 上的显示

android - Uncaught ReferenceError : LocalFileSystem is not defined in CORDOVA

node.js - 未找到命令 : nodemon --- need helping adding directory to PATH

asp.net - 在 Web.Config Location Path 元素中指定多个目录

ios - 从 UITableViewCell 的 accessoryView 中的自定义按钮获取索引路径

ios - iOS:如何在键盘按键后停止接收keyboardWillShowNotification

java - 如何将 SmbFile 转换为 File?

c# - 在 C#.Net 中创建 .dll 文件

量化线段路径差异的算法