Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
898 views
in Technique[技术] by (71.8m points)

objective c - Get the type of a file in Cocoa

I succeeded to find the extended file type of a specified file ( JPEG image, TIFF Image, ...) but I am looking for something more generic that can categorize files in "big cathegories" like images, moovies, text files, ... It there a way to acheive this in cocoa (or objective-c) ?

Thanks for your help,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...