Home > Mobile >  MacOS: how to get "Last opened" attribute of file?
MacOS: how to get "Last opened" attribute of file?

Time:10-13

In some files in OS exist "Last opened" attribute:

enter image description here

modified and opened attribute is possible to get by the following way:

//modified date
try? FileManager.default.attributesOfItem(atPath: url.path)[FileAttributeKey.modificationDate] as? Date

//creation date
try? FileManager.default.attributesOfItem(atPath: url.path)[FileAttributeKey.creationDate] as? Date

But how to get "Last opened" date?

CodePudding user response:

Leo's suggestion in comments to use URLResourceValues.contentAccessDate is probably the cleanest way, especially since you already have a URL, which is typically the case these days.

func lastAccessDate(forURL url: URL) -> Date?
{
    return try? url.resourceValues(
        forKeys: [.contentAccessDateKey]).contentAccessDate
}

You can also reach down into the BSD layer using the path:

import Darwin // or Foundation

func lastAccessDate(forFileAtPath path: String) -> Date?
{
    return path.withCString
    {
        var statStruct = Darwin.stat()
        guard  stat($0, &statStruct) == 0 else { return nil }
        return Date(
            timeIntervalSince1970: TimeInterval(statStruct.st_atimespec.tv_sec)
        )
    }
}

I'm not 100% of the of the behavior of resourceValues if the path specified is a symbolic link, but stat() will return information about the file system inode pointed to by the link. If you want information directly about the link itself, use lstat() instead. stat() and lstat() are the same otherwise.

CodePudding user response:

hah, some of metadata is accessible only from Spotlight.

So you need to use MDItem to get those parameter -- kMDItemLastUsedDate

extension URL {
    var lastOpenDate: Date? {
        guard isFileURL else { return nil }
        return MDItemCopyAttribute(MDItemCreateWithURL(kCFAllocatorDefault, self as CFURL), kMDItemLastUsedDate) as? Date
    }
}
  • Related