Reputation: 1748
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.
Upvotes: 0
Views: 742
Reputation: 758
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
})
Upvotes: 3
Reputation: 535118
would they already be in "date added" order?
No. contentsOfDirectory
is basically just alphabetical if it has any order at all. Sorting by age would be entirely up to you.
It is mere coincidence that in your example age order and returned order are the same.
Upvotes: 3