我编写了在文档目录中检索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排序的数组,而不是按字母数字排序的数组。非常感谢您的帮助。
您需要声明一个struct
具有URL(或文件名字符串)和Date的。从您从FileManager查询的文件(及其创建日期)中填充此结构的数组。
使用该结构数组作为表视图的数据模型。您可以按文件名或日期(或将来可能添加的任何其他属性)对数组进行排序。
您可以通过首先添加[.creationDateKey]
的includingPropertiesForKeys
参数来获取每个文件的创建日期contentsOfDirectory
。然后resourceValues
在每个URL上使用创建日期。请参阅如何在Swift 3中使用URL resourceValues方法获取文件创建日期?有关获取创建日期的更多详细信息。
使用代替的enumerator
方法可能会有所帮助。这将使获取需求URL属性和填充结构数组变得更加容易。FileManager
contentsOfDirectory
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句