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

问题描述 投票:1回答:1

我编写了代码来检索文档目录中的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排序的数组而不是字母数字。非常感谢您的帮助。

swift url
1个回答
1
投票

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

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

您可以通过首先将[.creationDateKey]添加到includingPropertiesForKeyscontentsOfDirectory参数来获取每个文件的创建日期。然后在每个URL上使用resourceValues访问创建日期。有关获取创建日期的更多详细信息,请参阅How can I get the file creation date using URL resourceValues method in Swift 3?

使用enumeratorFileManager方法代替contentsOfDirectory可能会有所帮助。这样可以更轻松地获取需求URL属性并填充struct数组。

© www.soinside.com 2019 - 2024. All rights reserved.