如何按创建日期对文件管理器数组进行排序

Nei*_*oth 5 url swift

我编写了代码来检索文档目录中的 CSV 路径并将它们加载到表格视图中。我试图按创建日期对文件进行排序,以便它们在表格视图中从最新到最旧列出。有人对如何实现这一目标有任何建议吗?

我还没有尝试过任何东西,因为我有点卡住了

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 ?? []


    }
Run Code Online (Sandbox Code Playgroud)

我需要按 .creationdate 排序的数组,而不是按字母数字排序。非常感谢您的帮助。

rma*_*ddy 3

您需要声明一个struct具有 URL(或文件名字符串)和日期的 。从您从 FileManager 查询的文件(及其创建日期)填充此结构的数组。

使用该结构数组作为表视图的数据模型。您可以按文件名或日期(或将来可能添加的任何其他属性)对数组进行排序。

您可以通过首先添加到 的参数[.creationDateKey]来获取每个文件的创建日期。然后使用每个 URL访问创建日期。请参阅如何在 Swift 3 中使用 URL ResourceValues 方法获取文件创建日期?有关获取创建日期的更多详细信息。includingPropertiesForKeyscontentsOfDirectoryresourceValues

使用enumerator的方法FileManager代替可能会有所帮助contentsOfDirectory。这将使获取所需的 URL 属性并填充结构数组变得更加容易。