My app uses iTunes File Sharing. The user can add files to the Documents directory.
I must read these files but make sure they're only images and not text files or other "garbage".
How can I iterate over the files in a directory and recognize only those which are images?
I assume that I would have to do it somehow 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 reasons. I would need a HUUUUUGE if-clause to catch all possible image file types, and there are DOZENS of them.
Is there a more intelligent way to really collect all image files, no matter if .png, .bmp, .jpg, .jpeg, .jpeg2000, .tiff, .raw, .etc?
I slightly remember that there were some kind of file attributes that told the general type of file. There was some abstract image key I believe. But maybe there's an even better method?
At first, we imported the pathlib module from Path. Then we pass the directory/folder inside Path() function and used it . glob('*. png') function to iterate through all the images present in this folder.
Import the OS module in your notebook. Define a path where the text files are located in your system. Create a list of files and iterate over to find if they all are having the correct extension or not. Read the files using the defined function in the module.
Yes you can, just use Uniform Type Identifiers. Here it 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);
Even if the filename suggests an image file, it doesn't neccessarily have to be an image. You could try to instanciate a UIImage
from the data and reject the file if it fails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With