find the last accessed date of a directory in swift

To find the last accessed date of a directory in Swift, you can use the FileManager class and its attributesOfItem method to get the attributes of the directory, including the FileAttributeKey.accessDate. Here's an example code snippet:

main.swift
let fileManager = FileManager.default
let directoryPath = "/path/to/directory"

do {
    let attributes = try fileManager.attributesOfItem(atPath: directoryPath)
    if let accessDate = attributes[.accessDate] as? Date {
        print("Last accessed date of directory: \(accessDate)")
    }
} catch {
    print("Error getting directory attributes: \(error)")
}
361 chars
12 lines

In this code, we first get the default file manager, then specify the path to the directory we want to get the last accessed date for. We then use a do-catch block to attempt to get the directory's attributes using attributesOfItem. If successful, we check the resulting attributes dictionary for a value under the .accessDate key, and print it out. If there's an error, we print out the error message.

gistlibby LogSnag