Getting an Uniform Type Identifier for a given extension
I needed this about a week ago:
NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,
(CFStringRef)[myFilePath pathExtension],
NULL);
If I run this on the extensions @"php", @"jpg", @"html", and @"ttf", it prints:
public.php-script
public.jpeg
public.html
public.truetype-ttf-font
Update 11+ years later:
In Swift, there are two ways to do this, depending on your deployment target:
If you want to run on macOS Catalina and earlier (before Big Sur) or iOS 13 and earlier:
let fileExtension = "html" let unmanagedString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension as CFString, fileExtension as CFString, nil) let typeIdentifier = unmanagedString?.takeRetainedValue() as String?
The
UTTypeCreatePreferredIdentifierForTag()
func (still part of theCoreServices
module) returns anUnmanaged<CFString>?
; this is a type that boxes aCFString
and you need to indicate (via one of the.take...
methods) what the memory management semantics should be.Since the function follows the Create Rule naming pattern, it's going to return a
CFString
to us that we need to take ownership of. Therefore we use.takeRetainedValue()
to transfer the ownership of theCFString
from the manual memory management world into the ARC world.Then there's a decent amount of bridging to go from
String
toCFString
and vice versa.macOS Big Sur (and iOS 14) got a new
UniformTypeIdentifiers
module that makes this a whole lot simpler:let fileExtension = "html" let typeIdentifier = UTType(filenameExtension: fileExtension)
You can use the Terminal and invoke mdls which gives you all kinds of information on a certain file type including UTIs.
mdls /myPath/to/myFile.ext
mdls will then show you the associated UTIs in kMDItemContentTypeTree (it's also possible to call mdls from within your Cocoa App btw).