FileManager: Attribute for when a file was last opened

381 views Asked by At

I need a way of checking when a file was last opened. I tried by creating a custom FileAttributeKey and setting that to the current Date, but when I go to open the file again the attribute does not exist:

private let key = FileAttributeKey(rawValue: "lastOpenedAt")
do {
    try FileManager.default.setAttributes(
        [key: Date()],
        ofItemAtPath: videoNameDirectoryPath
    )
} catch {
    Log.error(error.localizedDescription)
}

So now I am resorting to using the modification date key to say when I last opened the file, it is not ideal so I am wondering if there is a better way to do this

1

There are 1 answers

0
mahal tertin On

setAttributes doesn't support custom attributes, you can only use the documented ones.

To set your own attributes, you may use xattr as described in this question:

Write extend file attributes swift example

If you're lucky, you may use kMDItemLastUsedDate from Spotlight aka MDItem as described in the documentation archive of File Metadata Attributes.