我一直在使用 Swift 的[enumerator(at:includingPropertiesForKeys:options:)]
1来查找给定基本路径中的所有文件,并为不同的资源键(文件名、路径、创建日期等)创建数组。这工作得很好,但我注意到创建的数组中的元素不是按创建日期排序的,这是我在将这些数组的元素传递到循环中以按日期顺序上传每个文件之前需要的。
因此,我需要以某种方式按创建日期对所有结果数组的元素进行排序,这是我能够在其自己的数组中提取的属性(使用 .creationDateKey 资源键)。因此,我有两个选择(我认为):
- 强制元素按其创建日期首先附加到原始数组
- 使用包含文件创建日期的数组对每个创建的数组的元素进行排序
最好的方法是什么?我认为这很简单,但没有发现它。
所有的建议都亲切地接受了。谢谢。
这是我的代码:
// get URL(s) and other attributes of file(s) to be uploaded
let localFileManager = FileManager()
let resourceKeys = Set<URLResourceKey>([.nameKey, .pathKey, .creationDateKey, .isDirectoryKey])
let directoryEnumerator = localFileManager.enumerator(at: baseURL, includingPropertiesForKeys: Array(resourceKeys), options: .skipsHiddenFiles)!
var fileURLs: [URL] = []
var fileNames: [String] = []
var filePaths: [String] = []
var fileDates: [Date] = []
for case let fileURL as URL in directoryEnumerator {
guard let resourceValues = try? fileURL.resourceValues(forKeys: resourceKeys),
let isDirectory = resourceValues.isDirectory,
let name = resourceValues.name,
let path = resourceValues.path,
let date = resourceValues.creationDate,
else {
continue
}
if isDirectory {
if name == "_extras" { // use this to exclude a given directory
directoryEnumerator.skipDescendants()
}
} else {
// append elements in date order here?
fileURLs.append(fileURL) // full URLs of files
fileNames.append(name) // file names only
filePaths.append(path) // paths of file
fileDates.append(date) // date and time that file was created
// sort arrays by creation date here?
}
}
print(fileURLs)
print(fileNames)
print(filePaths)
print(fileDates)