我写了一些代码,用于在documents目录中检索CSV路径并将其加载到表格视图中。我试图按创建日期对文件进行排序,以便它们在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而不是字母数字排序的数组。非常感谢您的帮助。
答案 0 :(得分:1)
您需要声明一个struct
,该URL具有URL(或文件名String)和Date。从您从FileManager查询的文件(及其创建日期)中填充此结构的数组。
使用该结构数组作为表视图的数据模型。您可以按文件名或日期(或将来可能添加的任何其他属性)对数组进行排序。
您可以通过将[.creationDateKey]
首先添加到includingPropertiesForKeys
的{{1}}参数中来获得每个文件的创建日期。然后在每个URL上使用contentsOfDirectory
访问创建日期。有关获取创建日期的更多详细信息,请参见How can I get the file creation date using URL resourceValues method in Swift 3?。
使用resourceValues
的{{1}}方法而不是enumerator
可能会有所帮助。这样可以更轻松地获取需求URL属性并填充struct数组。