我编写了代码来检索文档目录中的CSV路径并将它们加载到tableview中。我试图按创建日期对文件进行排序,以便它们在tableview中从最新到最旧列出。有人对如何完成这个有任何建议吗?
我还没有尝试任何东西,因为我有点卡住了
override func viewDidLoad() {
super.viewDidLoad()
csvFiles = listCsvs()
tblViewDataCSV.dataSource = self
tblViewDataCSV.delegate = self
}
func listCsvs() -> [URL] {
let fileManager = FileManager.default
let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let files = try? fileManager.contentsOfDirectory(
at: documentDirectory,
includingPropertiesForKeys: nil,
options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles]
).filter {
$0.lastPathComponent.hasSuffix(".csv")
}
print(files as Any)
return files ?? []
}
我需要按.creationdate排序的数组而不是字母数字。非常感谢您的帮助。
您需要声明一个具有URL(或文件名字符串)和日期的struct
。从您从FileManager查询的文件(及其创建日期)填充此结构的数组。
使用该struct数组作为表视图的数据模型。您可以对文件名或日期(或将来可能添加的任何其他属性)对数组进行排序。
您可以通过首先将[.creationDateKey]
添加到includingPropertiesForKeys
的contentsOfDirectory
参数来获取每个文件的创建日期。然后在每个URL上使用resourceValues
访问创建日期。有关获取创建日期的更多详细信息,请参阅How can I get the file creation date using URL resourceValues method in Swift 3?。
使用enumerator
的FileManager
方法代替contentsOfDirectory
可能会有所帮助。这样可以更轻松地获取需求URL属性并填充struct数组。