Tom Lilletveit
Tom Lilletveit

Reputation: 2002

Getting all attributes for stored objects in filesystem directory in iOS

I know of this method: resourceValueForKeys which given an NSURL and a array of keys will fetch the attribuest of the file for you... But what I need is something that enumerates through all files in a given NSURL directory and gives me the attributes.

I tried doing this with an enumerator in NSFileSystem class but could not get it to work, anyone know the right way to do this?... I am not using Core Data.

   NSDictionary *values = [fileDirectory resourceValuesForKeys:@[NSURLAttributeModificationDateKey] error:nil];
    NSLog(@"object: %@", values);

Upvotes: 2

Views: 1070

Answers (2)

Gabriel
Gabriel

Reputation: 3359

To enumerate through all files in a given directory:

NSArray * arrayOfURLs = [fileManager contentsOfDirectoryAtURL:URL includingPropertiesForKeys:@[NSURLIsDirectoryKey,
        NSURLNameKey,NSURLFileSizeKey,NSURLContentModificationDateKey,
        NSURLLocalizedTypeDescriptionKey]
                              options:NSDirectoryEnumerationSkipsHiddenFiles 
                                error:nil];

for ( NSURL file in arrayOfURLs ) {
    NSString * nameOfFile;
    [file getResourceValue:&nameOfFile forKey:NSURLNameKey error:nil];
    NSLog(@"%@", nameOfFile);

    ...... and so forth for the rest of values ...

}

this way you can get all the values for all the files contained in the folder.

Upvotes: 2

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 2451

Here you go:

NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/your file path"];
NSLog(@"Your path: %@",path);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSDictionary *attributesOfYourItem = [fileManager attributesOfItemAtPath:path error:&error];
if(error)
    NSLog(@"Error: %@",error);
else
    NSLog(@"Attribute dictionary: %@",attributesOfYourItem);

Upvotes: 5

Related Questions