How could I get the date from each file in the directory ?
let directoryContent = try fileManager.contentsOfDirectory(atPath: directoryURL.path)
That's how i get files from directory. I found a few methods :
directoryContent.Contains(...)
The file where data is older then few days - how could i check it ?
then;
let fileAttributes = try fileManager.attributesOfItem(atPath: directoryURL.path)
It is going to give me last file in the directory.
And this going to return date in bytes :
for var i in 0..<directoryContent.count {
let date = directoryContent.index(after: i).description.data(using: String.Encoding.utf8)!
print(date)
}
Which one is the best way to recive the date from all files or check if the directory conteins specific dates which are older then X time.
Thanks in advance!
It's highly recommended to use the URL
related API of FileManager
to get the file attributes in a very efficient way.
This code prints all URLs of the specified directory with a creation date older than a week ago.
let calendar = Calendar.current
let aWeekAgo = calendar.date(byAdding: .day, value: -7, to: Date())!
do {
let directoryContent = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: [.creationDateKey], options: .skipsHiddenFiles)
for url in directoryContent {
let resources = try url.resourceValues(forKeys: [.creationDateKey])
let creationDate = resources.creationDate!
if creationDate < aWeekAgo {
print(url)
// do somthing with the found files
}
}
}
catch {
print(error)
}
If you want finer control of the workflow for example an URL is invalid and you want to print the bad URL and the associated error but continue precessing the other URLs use an enumerator, the syntax is quite similar:
do {
let enumerator = fileManager.enumerator(at: directoryURL, includingPropertiesForKeys: [.creationDateKey], options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles], errorHandler: { (url, error) -> Bool in
print("An error \(error) occurred at \(url)")
return true
})
while let url = enumerator?.nextObject() as? URL {
let resources = try url.resourceValues(forKeys: [.creationDateKey])
let creationDate = resources.creationDate!
if creationDate < last7Days {
print(url)
// do somthing with the found files
}
}
}
catch {
print(error)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With