Neil Bergenroth
Neil Bergenroth

Reputation: 125

How to sort the filemanager array by creation date

I have written code that retrieves CSV paths in the documents directory and loads them into a tableview. I am trying to sort the files by creation date so that they list from newest to oldest in the tableview. Anyone got any advice on how to accomplish this?

I've not tried anything yet, because I am a little stuck

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


    }

I need the array sorted by .creationdate and not alphanumerically. Many thanks for your help.

Upvotes: 5

Views: 2301

Answers (2)

Isidoros Moulas
Isidoros Moulas

Reputation: 697

You can build a struct like the below:

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

For each file in folder, append your struct into array.

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

At this point, you have an array with your files and filedates.

And finally sort the array with:

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

Upvotes: 1

rmaddy
rmaddy

Reputation: 318944

You need to declare a struct that has a URL (or filename String) and a Date. Populate an array of this struct from the files (and their creation dates) you query from FileManager.

Use that array of struct as your data model for the table view. You can sort the array on filename or date (or any other attributes you might add in the future).

You can get the creation date of each file by first adding [.creationDateKey] to the includingPropertiesForKeys parameter of contentsOfDirectory. Then access the creation date using resourceValues on each URL. See How can I get the file creation date using URL resourceValues method in Swift 3? for more details on getting the creation date.

It may help to use the enumerator method of FileManager instead of contentsOfDirectory. This will make it easier to get the needs URL attributes and populate the array of struct.

Upvotes: 3

Related Questions