find the last modified date of a file in swift

You can find the last modified date of a file in Swift using the FileManager class. Here's an example code that shows how to do it:

main.swift
let filePath = "/path/to/your/file"
let fileManager = FileManager.default

do {
    let attributes = try fileManager.attributesOfItem(atPath: filePath)
    if let modificationDate = attributes[.modificationDate] as? Date {
        print("The file was last modified on: \(modificationDate)")
    }
} catch {
    print("Error: \(error)")
}
338 chars
12 lines

In this code, we first specify the path to the file we want to check (filePath). We then create an instance of the FileManager class (fileManager). We then use the attributesOfItem method of the FileManager class to get the file attributes (including the modification date) of the file at the specified path.

We check if the attributes dictionary contains a modificationDate key. If it does, we extract the Date object associated with this key and print it. If the attributes dictionary doesn't contain a modificationDate key, it means that the file doesn't exist, or we don't have permission to read it, etc. Therefore, we output an error message in this case.

gistlibby LogSnag