Skip to content

Instantly share code, notes, and snippets.

@ddeville
Created December 28, 2011 10:40
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ddeville/1527517 to your computer and use it in GitHub Desktop.
Save ddeville/1527517 to your computer and use it in GitHub Desktop.
MIME type to UTI and back again in Cocoa
#if TARGET_OS_IPHONE
#import <MobileCoreServices/MobileCoreServices.h>
#else
#import <CoreServices/CoreServices.h>
#endif
/*
MIME type to UTI
*/
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;
/*
UTI to MIME type
*/
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;
@nalexn
Copy link

nalexn commented Sep 22, 2020

Swift:

// - MIME to UTI

let mimeType: String = "image/jpeg"
let utType: String? = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType as CFString, nil)?.takeRetainedValue() as String

// - UTI to MIME

let utType: String = "public.jpeg"
let mimeType: String? = UTTypeCopyPreferredTagWithClass(utType as CFString, kUTTagClassMIMEType)?.takeRetainedValue() as String

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment