Get the type of a file in Cocoa

You could use Uniform Type Identifiers. Since UTIs are organised into hierarchies, one possibility is to check whether the preferred UTI for a given file conforms to a top-level UTI, e.g. public.image for images or public.movie for movies. The Core Services framework includes functions that operate on UTIs as well as constants representing known UTIs.

For instance, working on file name extensions:

NSString *file = @"…"; // path to some file
CFStringRef fileExtension = (CFStringRef) [file pathExtension];
CFStringRef fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);

if (UTTypeConformsTo(fileUTI, kUTTypeImage)) NSLog(@"It's an image");
else if (UTTypeConformsTo(fileUTI, kUTTypeMovie)) NSLog(@"It's a movie");
else if (UTTypeConformsTo(fileUTI, kUTTypeText)) NSLog(@"It's text");

CFRelease(fileUTI);

If you have a MIME type instead of a file name extension, you can use kUTTagClassMIMEType instead of kUTTagClassFilenameExtension.

For a list of known UTIs, see this document.

Leave a Comment