Search code examples
objective-cfile-type

get extension's human friendly description of a given extension


I'm sure there's a way to get a human friendly description of a file's extension in objective-c - cocoa. For example: given an extension "pdf" to get "Portable Document Format", or given "app" -> "Application", or "txt" -> "Plain Text", etc.


Solution

  • You can do it with some the UT* functions:

    NSString * humanReadableStringForExtension(NSString * extension) {
        CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)extension, NULL);
        NSString * extensionDescription = (NSString *)UTTypeCopyDescription(UTI);
        CFRelease(UTI);
        return [extensionDescription autorelease];
    }
    

    You can then do stuff like:

    NSLog(@"pdf: %@", humanReadableStringForExtension(@"pdf"));
    NSLog(@"txt: %@", humanReadableStringForExtension(@"txt"));
    NSLog(@"app: %@", humanReadableStringForExtension(@"app"));
    

    Which will log:

    pdf: Portable Document Format (PDF)
    txt: text
    app: application
    

    (woot, my 1000th answer!)