find the last accessed date of a file in swift

To find the last accessed date of a file in Swift, you can use the FileManager class to get the file attributes, including the file's access date. Here is a code snippet for finding the last access date of a file:

main.swift
let fileManager = FileManager.default
let filePath = "path/to/file"
do {
    let attributes = try fileManager.attributesOfItem(atPath: filePath)
    if let accessDate = attributes[.accessDate] as? Date {
        // use the accessDate value
        print("Last access date: \(accessDate)")
    }
} catch {
    print("Error getting file attributes: \(error.localizedDescription)")
}
381 chars
12 lines

In the code above, we first create an instance of the FileManager class, and then specify the path to the file we want to get attributes for. We then use the attributesOfItem method to get the attributes dictionary for the file. Finally, we retrieve the value for the .accessDate key from the attributes dictionary, which gives us the last access date of the file.

gistlibby LogSnag