Chris Barrett
Chris Barrett

Reputation: 601

Find latest modified file in Folder

I'm trying to find the latest text file in a folder so I can open it. So far I have:

let logFolder = URL(fileURLWithPath: "/Users/me/Library/Logs" )
let fm = FileManager.default

var files = try fm.contentsOfDirectory(at: logFolder, includingPropertiesForKeys: [.creationDateKey], options: [])
let txtFilePaths = files.filter{$0.pathExtension == "txt"}

But then I get stuck. I know I can get the date for a file with txtFilePath[x].creationDate

Seems like there should be a simple way of doing this but I'm a newbie and struggling to find any web resources for Swift 5.

Cheers

Upvotes: 0

Views: 1045

Answers (2)

Paul B
Paul B

Reputation: 5115

Try this one:

extension FileManager {
    
    func latestModifiedFile(at directoryURL: URL) -> URL? {
        guard let fileURLs = try? contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: [.contentModificationDateKey], options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles]) else { return nil }
        let txtFileURLs = fileURLs.filter{ $0.pathExtension == "txt" }
        let sortedtxtFilePaths = txtFileURLs.sorted { (url1, url2) -> Bool in
            do {
                let values1 = try url1.resourceValues(forKeys: [.contentModificationDateKey])
                let values2 = try url2.resourceValues(forKeys: [.contentModificationDateKey])
                return values1.creationDate ?? .distantPast < values2.creationDate ?? .distantPast
            } catch {
                return false // If sorting fails, keep order
            }
        }
        return sortedtxtFilePaths.last
    }
    
}

Usage:

let latestModifiedTextFile = FileManager.default.latestModifiedFile(at: URL(...))

Upvotes: 0

Dragos Popa
Dragos Popa

Reputation: 31

Such information about files is stored in something that is usually referred to as metadata.

I believe you are looking for something like NSMetadataItem.

By following the steps presented in this response, you should be able to have access to a field called kMDItemContentModificationDate. This should help you achieve your goal.

Upvotes: 1

Related Questions