Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the Last Accessed Date of a File in Cocoa

Is it possible to get file/folder last accessed date in mac using cocoa?

    struct stat output;
    //int ret = stat([[[openPanel filenames] lastObject] UTF8String], &output);
    int ret = stat([[[openPanel filenames] lastObject] fileSystemRepresentation], &output);
    // error handling omitted for this example
    struct timespec accessTime = output.st_atimespec;

    NSDate *aDate = [NSDate dateWithTimeIntervalSince1970:accessTime.tv_sec];

    NSLog(@"Access Time %d, %@",ret, aDate);

As per the above code i have tried both UTF8String and fileSystemRepresentation, but both are giving me current date and time.Please let me know if i am doing anything wrong.

like image 990
AmitSri Avatar asked May 14 '10 09:05

AmitSri


3 Answers

The C way of doing it, using the stat system call will work in Objective-C.

e.g.

struct stat output;
int ret = stat(aFilePath, &output);
// error handling omitted for this example
struct timespec accessTime = output.st_atime;

You should get aFilePath by sending -fileSystemRepresentation to an NSString containing the path.

Another way you might get what you want is to construct an NSURL fore a file URL pointing to the file you want and using -resourceValuesForKeys:error: to get the NSURLContentAccessDate resource value.

like image 81
JeremyP Avatar answered Nov 03 '22 07:11

JeremyP


Using NSMetadataQuery you can access spotlight metadata from your code. The last used date attribute of a file is tracked by spotlight and you can access that with this property: kMDItemLastUsedDate.

like image 2
regulus6633 Avatar answered Nov 03 '22 07:11

regulus6633


NSURL/URL's resource values can provide this:

let url: URL = ...
let values = try url.resourceValues(forKeys: [.contentAccessDateKey])
let accessed: Date? = values.contentAccessDate
like image 2
Adam Preble Avatar answered Nov 03 '22 07:11

Adam Preble