Как отсортировать изображения uiimages по дате из папки приложения в ios [дубликат]

StackOverflow https://stackoverflow.com//questions/20000208

  •  20-12-2019
  •  | 
  •  

Вопрос

Как отображать изображения по типу сортировки по дате изменения из галереи.Я могу получить данные из папки, используя

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

    NSFileManager *manager = [NSFileManager defaultManager];

Также как сравнить uiimage по дате изменения.

Заранее спасибо....

Это было полезно?

Решение

Самый простой способ:

- (void)images
{

    //---Get directory from app folder
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *imageFilenames = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
    NSMutableArray *originalImage = [[NSMutableArray alloc]init];

    for (int i = 1; i < [imageFilenames count]; i++)
    {
        NSString *imageName = [NSString stringWithFormat:@"%@/%@",documentsDirectory,[imageFilenames objectAtIndex:i] ];
        UIImage *image = [UIImage imageWithContentsOfFile:imageName];
        [originalImage addObject:image];
    }
    NSLog(@"\n\n\n Original images %@",originalImage);



    //---------sorting image by date modified
    NSArray*  filelist_date_sorted;

    filelist_date_sorted = [imageFilenames sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
                            {
    NSDictionary* first_properties  = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", documentsDirectory, obj1] error:nil];
    NSDate *first = [first_properties  objectForKey:NSFileModificationDate];
NSDictionary *second_properties = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", documentsDirectory, obj2] error:nil];
    NSDate *second = [second_properties objectForKey:NSFileModificationDate];
    return [second compare:first];
    }];
    NSLog(@"\n\n\n date images %@",filelist_date_sorted);
    NSMutableArray *sortedImage = [[NSMutableArray alloc]init];

    //--- Store sorted images in array

    for (int i = 1; i < [imageFilenames count]; i++)
    {
        NSString *imageName = [NSString stringWithFormat:@"%@/%@",documentsDirectory,[filelist_date_sorted objectAtIndex:i] ];
        UIImage *image = [UIImage imageWithContentsOfFile:imageName];
        if(!(image==nil))
        {
            [sortedImage addObject:image];
        }

    }

    NSLog(@"\n\n\nsorted images %@",sortedImage);

}

Другие советы

Для этого вам придется использовать Библиотека ALAssets для перечисления всех изображений из галереи.

Отсюда вы можете получить атрибуты каждого изображения:

  • имя файла изображения.
  • URL-адрес ресурса изображения

и твой ответ здесь:

Вы можете получить дату создания актива, используя Алассетпропертидате свойство:

  ALAsset* asset;
   //do anthing 
  NSDate* date = [asset valueForProperty:ALAssetPropertyDate];

возможно, это поможет вам.

Вы можете получить атрибуты изображения, используя этот код

NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:@"path/to/my/file" error:nil];

Вы можете получить дату изменения, используя этот код

NSDate *date = [attributes fileModificationDate];

Создайте NSmutableDictionary и поместите измененную дату в качестве ключа и путь в качестве значения.

NSMutableDictionary *imagesDict = [[NSMutableDictionary alloc] init];

for(NSString *path in paths)
{
  NSDictionary *attributes = [[NSFileManager defaultManager] ;
  NSDate *date = [attributes fileModificationDate];
  imagesDict[date] = path; // key - date  ,    value - path
}

Затем вы можете сортировать ключи imagesDict

NSArray *sortedDates = [[imagesDict allKeys]  sortedArrayUsingSelector:@selector(compare:)];

а затем вы можете создать цикл для элементов sortedDates и отсортировать их по путям дат для ваших изображений.

for(NSDate *newDate in sortedDates)
{
  NSString newPath = imagesDict[newDate];
}

Другое решение:

-(NSArray *)orderedFileListByModificationDate{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *dirPath = [paths objectAtIndex:0];
    dirPath=[dirPath stringByAppendingString:@"/imgs"];

    NSFileManager *fileManager=[[NSFileManager alloc] init];
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zz"];

    int filesCount;
    NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dirPath error:NULL];
    int dirFilesCount=(int)[directoryContent count];
    NSMutableArray *fileObjects=[NSMutableArray array];
    for (filesCount = 0; filesCount < dirFilesCount; filesCount++)
    {
        NSString *fileName=[directoryContent objectAtIndex:filesCount];
        NSString *filePath =[NSString stringWithFormat:@"%@/%@",dirPath,fileName];

        NSDictionary *fileAttributes=[fileManager attributesOfItemAtPath:filePath error:nil];
        NSDate *dateModiftication=[fileAttributes valueForKey:@"NSFileModificationDate"];

        NSMutableDictionary *datesAndFilesDict=[[NSMutableDictionary alloc] initWithCapacity:2];
        [datesAndFilesDict setValue:fileName forKey:@"fileName"];
        [datesAndFilesDict setValue:dateModiftication forKey:@"date"];

        [fileObjects addObject:datesAndFilesDict];
    }

    NSLog(@"%@",fileObjects);
    NSArray *newOrderedFileList = [fileObjects sortedArrayUsingComparator:
                                            ^(id obj1, id obj2) {
                                                NSDate *dateOne=[(NSDictionary*)obj1 valueForKey:@"date"];
                                                NSDate *dateTwo=[(NSDictionary*)obj2 valueForKey:@"date"];
                                                NSComparisonResult result=[dateOne compare:dateTwo];
                                                return result;
                                            }];
    NSLog(@"%@",newOrderedFileList);
    //Now you've an array of dictionaries where you can pick the filename with the "fileName" key.
    return newOrderedFileList;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top