Often when working with web services in Cocoa, I need to convert between MIME type and Uniform Type Identifier (UTI).
I have seen many hacky way to do this but, in my opinion, following is the correct way to achieve it.
First let’s import the appropriate framework based on the platform (you might also need to add the framework to your project if not previously done).
#if TARGET_OS_IPHONE #import <MobileCoreServices/MobileCoreServices.h> #else #import <CoreServices/CoreServices.h> #endif
To get the UTI from a MIME type.
NSURLResponse *response = ... // assume a URL response from somewhere else. NSString *responseMIMEType = [response MIMEType]; CFStringRef MIMEType = (__bridge CFStringRef)[response MIMEType]; CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, MIMEType, NULL); NSString *UTIString = (__bridge_transfer NSString *)UTI;
And to get the MIME type from the UTI.
NSString *filePath = ... // assume the path to a file from somewhere else. CFStringRef fileExtension = (__bridge CFStringRef)[filePath pathExtension]; CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL); CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType); CFRelease(UTI); NSString *MIMETypeString = (__bridge_transfer NSString *)MIMEType;
Interested in working with me on amazing products used by millions of people? My team at Dropbox is hiring, get in touch!