Search code examples
iosswiftnsfilemanager

Are files in iOS automatically sorted by date added?


I was wondering if I added a bunch of files to the Documents directory using FileManager, and at a later time retrieved them, would they already be in "date added" order? I.e., oldest will be first in the array and newest will be last in the array.

I'm asking this because in the simulator if I do fm.createFile(atPath: ".../Documents/hello1.txt", contents: someData, attributes: nil) and then do fm.createFile(atPath: ".../Documents/hello2.txt", contents: someData, attributes: nil) and retrieve them, they show up in order (hello1 being first then hello2). I was wondering if this behaviour will always be consistent. If it is then I can just do fm.contentsOfDirectory(atPath: .../Documents).first! to get the oldest file in my directory.

Please let me know if this behaviour will be consistent on an actual iOS device.

Thanks in advance.


Solution

  • Short answer is no. The order cannot be guaranteed at run time. You'll have to sort the array yourself. I suggest trying something like this instead.

        let orderedURLs = try? FileManager.default.contentsOfDirectory(at: myDirectoryUrl, includingPropertiesForKeys: [.creationDateKey], options: .skipsHiddenFiles).sorted(by: {
            if let date1 = try? $0.resourceValues(forKeys: [.creationDateKey]).creationDate,
               let date2 = try? $1.resourceValues(forKeys: [.creationDateKey]).creationDate {
                return date1 < date2
            }
            return false
        })