Reputation: 46400
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?
Upvotes: 6
Views: 4396
Reputation: 9453
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);
Upvotes: 10
Reputation: 35394
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.
Upvotes: 5