【问题标题】:How to sort the filemanager array by creation date如何按创建日期对文件管理器数组进行排序
【发布时间】:2019-04-21 04:47:59
【问题描述】:

我编写了检索文档目录中的 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 ?? []


    }

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

【问题讨论】:

    标签: swift url


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

      您可以构建如下结构:

      struct yourStruct {
          var path:URL
          var filedate:Date
      }
      

      对于文件夹中的每个文件,将结构附加到数组中。

      let s = yourStruct(
                 path: csvUrl,
                 filedate: csvFileDate)
      myArray.append(s)  
      

      此时,您有一个包含文件和归档日期的数组。

      最后对数组进行排序:

      let newArr = myArray.sorted { $0.filedate < $1.filedate }
      

      【讨论】:

        猜你喜欢
        • 2011-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-07
        • 1970-01-01
        • 1970-01-01
        • 2013-10-26
        相关资源
        最近更新 更多