I have a list of image in Document folder of app.And I want to load images in order of date created. How can I do that ?
Asked
Active
Viewed 1,367 times
2 Answers
5
This code will enumerate all files in your documents directory in the order they were created:
See comments in the code to understand what is going on.
NSFileManager *fm = [NSFileManager defaultManager];
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *err;
// Get all files with their creation date
NSArray *files = [fm contentsOfDirectoryAtURL:[[NSURL alloc] initFileURLWithPath:doc isDirectory:YES]
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLCreationDateKey]
options:0
error:&err];
// Using file's URL as the key, store creation date as the value
NSMutableDictionary *urlWithDate = [NSMutableDictionary dictionaryWithCapacity:files.count];
for (NSURL *f in files) {
NSDate *creationDate;
if ([f getResourceValue:&creationDate forKey:NSURLCreationDateKey error:&err]) {
[urlWithDate setObject:creationDate forKey:f];
}
}
// Sort the dictionary on the value, which is the creation key
for (NSURL *f in [urlWithDate keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 compare:obj2];
}]) {
// Check if the file is an image. Load if it is an image, otherwise skip.
NSLog(@"%@", f);
}

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
-
Nice to see how to load all files with their attributes in one single request – tothemario Oct 02 '15 at 00:53
1
I would take a look: Getting a list of files in a directory with a glob
Specifically the NSFileManager. You can look at attributes of the file. From there you can most likely do a sort using NSPredicate.

Community
- 1
- 1

James Paolantonio
- 2,194
- 1
- 15
- 32