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

Get fullpath or convert to fullpath

使用时

let directoryEnumerator = FileManager().enumerator(at: ...

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

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

结果不包括前导路径(此处为“/Volumes/MacOS”)。所以我得到

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

如何获取完整路径(直接从枚举器获取)或转换它们。我想使用 URL 函数,而不是通过假设操作的字符串函数。

请注意,您希望尽可能使用 URL,来自 NSURL documentation:

URL objects are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept an NSURL object instead of a pathname as the file reference.

这是一个如何从目录中获取所有对象的示例:

import Foundation

let manager = FileManager.default

// Get URL for the current user’s Documents directory
// Use URL instead of path, it’s more flexible and preferred
if let documents = manager.urls(for: .documentDirectory, in: .userDomainMask).first,

  // Get an Enumerator for the paths of all the objects in the directory
  // but do not descend into directories or packages
  let directoryEnumerator = manager.enumerator(at: documents, includingPropertiesForKeys: [URLResourceKey.pathKey], options: [.skipsSubdirectoryDescendants, .skipsPackageDescendants]) {

  // iterate through the objects (files, directories, etc.) in the directory
  for path in directoryEnumerator {
    print(path)
  }
}

如果"MacOS"是你当前启动盘的名字,那么“/Volumes/MacOS”是一个符号link到“/”,所以“/fasttemp/Fotos/2005/”和“/Volumes/MacOS/fasttemp/Fotos/”是同一文件的绝对路径。

为了获得唯一的文件名表示,您可以查询 a 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([=11=], nil) }) {
    let fullUrl = URL(fileURLWithFileSystemRepresentation: rp, isDirectory: true, relativeTo: nil)
    free(rp)
    print(fullUrl.path)
}
// Output: "/Applications/Utilities"