Search code examples
objective-cnsfilemanager

How to find all contents with modified date of the directory in Objective C code


This requirement is very specific to read directory contents along with date modified for all sub files and folders. In windows we have some API's but I didn't find similar function in Mac OS development. I searched for this where I found that NSFileManager can be used for this.I found one place where I can get the path contents under Documents directory.

Here is the piece of code code which I have.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];

NSFileManager *manager = [[NSFileManager alloc] init];
NSDirectoryEnumerator *fileEnumerator = [manager enumeratorAtPath:documentsPath];

for (NSString *filename in fileEnumerator) {
    // Do something with file
    NSLog(@"file name : %@",filename );
}

But my requirement is to find the contents under any path on machine with the date modified for all sub files and a folders in it.Please guide me on it.

Thanks, Tausif.


Solution

  • Apple has a code sample demonstrating how to do this:

    NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:directoryPath];
    
    NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:(-60*60*24)];
    
    for (NSString *path in directoryEnumerator) {
    
        if ([[path pathExtension] isEqualToString:@"rtfd"]) {
            // Don't enumerate this directory.
            [directoryEnumerator skipDescendents];
        } else {
            NSDictionary *attributes = [directoryEnumerator fileAttributes];
            NSDate *lastModificationDate = [attributes objectForKey:NSFileModificationDate];
    
            if ([yesterday earlierDate:lastModificationDate] == yesterday) {
                NSLog(@"%@ was modified within the last 24 hours", path);
            }
        }
    }
    

    Basically this code enumerates the directoryPath and checks if the file or directory has been modified within the last 24 hours.