Skip to content

Instantly share code, notes, and snippets.

@drewmccormack
Created July 14, 2011 13:05
Show Gist options
  • Save drewmccormack/1082407 to your computer and use it in GitHub Desktop.
Save drewmccormack/1082407 to your computer and use it in GitHub Desktop.
NSURL category method to get the UTI of a file
@implementation NSURL (MCExtensions)
-(NSString *)UTI
{
FSRef fileRef;
Boolean isDirectory;
NSString *utiString = nil;
if ( !self.isFileURL ) return nil;
if (FSPathMakeRef((const UInt8 *)[self.path fileSystemRepresentation], &fileRef, &isDirectory) == noErr) {
CFDictionaryRef values = NULL;
CFStringRef attrs[1] = { kLSItemContentType };
CFArrayRef attrNames = CFArrayCreate(NULL, (const void **)attrs, 1, NULL);
if (LSCopyItemAttributes(&fileRef, kLSRolesViewer, attrNames, &values) == noErr) {
if (values != NULL) {
CFTypeRef uti = CFDictionaryGetValue(values, kLSItemContentType);
if (uti != NULL) {
utiString = [[(id)uti copy] autorelease];
}
CFRelease(values);
}
}
CFRelease(attrNames);
}
return utiString;
}
@end
@drewmccormack
Copy link
Author

After writing this, I realized that NSWorkspace already has a method to get the UTI (typeOfFile:error:). I'll leave this here in case it is useful just to see how you can use the C APIs to work with UTIs.

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