How to iterate over all image files in a directory?

My app uses iTunes file sharing. The user can add files to the Documents directory.

I have to read these files, but make sure that they are only images, not text files or other โ€œjunkโ€.

How can I iterate over files in a directory and only recognize those that are images?

I guess I would have to do it like this:

NSMutableArray *retval = [NSMutableArray array]; NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirPath error:&error]; if (files == nil) { // error... } for (NSString *file in files) { if ([file.pathExtension compare:@"png" options:NSCaseInsensitiveSearch] == NSOrderedSame) { NSString *fullPath = [documentsDirPath stringByAppendingPathComponent:file]; [retval addObject:fullPath]; } } 

But this is bad for some reason. I will need HUUUUUUGE if-clause to catch all possible types of image files, and there are DOSES.

Is there a smarter way to really collect all image files, regardless of whether they are .png, .bmp, .jpg, .jpeg, .jpeg2000, .tiff, .raw, .etc?

I remember a little that there were some file attributes that talked about the general type of file. I believe that there is some kind of abstract image. But maybe there is an even better method?

+6
source share
2 answers

Yes, you can use Unified Type Identifiers . There he is:

 NSString *file = @"โ€ฆ"; // path to some file CFStringRef fileExtension = (CFStringRef) [file pathExtension]; CFStringRef fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL); if (UTTypeConformsTo(fileUTI, kUTTypeImage)) NSLog(@"This is an image"); CFRelease(fileUTI); 
+10
source

Even if a file name suggests an image file, it does not have to be an image. You can try installing UIImage from the data and reject the file if it does not work.

+5
source

Source: https://habr.com/ru/post/889032/


All Articles