Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine MIME Type of NSData Loaded From a File

For various reasons I am intercepting http requests and loading content from files in my app's document directory using NSURLProtocol. Part of the process involves loading an NSData object, which could be anything from an html file to a jpeg image. NSURLProtocol requires setting a mimetype.

Is there an API in the iPhone-SDK to determine the mimetype of the file or NSData content?

like image 473
JoBu1324 Avatar asked May 13 '11 19:05

JoBu1324


1 Answers

Perhaps you could download the file and use this to get the file's MIME type.

+ (NSString*) mimeTypeForFileAtPath: (NSString *) path {
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return nil;
    }
    // Borrowed from https://stackoverflow.com/questions/5996797/determine-mime-type-of-nsdata-loaded-from-a-file
    // itself, derived from  https://stackoverflow.com/questions/2439020/wheres-the-iphone-mime-type-database
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)[path pathExtension], NULL);
    CFStringRef mimeType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
    CFRelease(UTI);
    if (!mimeType) {
        return @"application/octet-stream";
    }
    return [NSMakeCollectable((NSString *)mimeType) autorelease];
}
like image 154
Alexsander Akers Avatar answered Nov 02 '22 04:11

Alexsander Akers