18

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?

JoBu1324
  • 7,751
  • 6
  • 44
  • 61
  • File extensions are your best friend, and when you can't determine the file type by extension and/or binary header on your own or using a 3rd party library you may find, then default the content to application/octet-stream. – Joe May 13 '11 at 19:31
  • I'm not familiar with such API in the SDK. However, if there no way to save the mime-type, then you can use [MagicKit](https://github.com/aidansteele/MagicKit). – Roman May 13 '11 at 19:34
  • very nice lib, thx Roman! – Martin Nov 23 '12 at 10:41
  • MagicKit does not work with recent Xcode, attempting to use it with CoccaPods also fails https://travis-ci.org/sugarso/S3ZencoderVideoManager/builds/25238603 https://groups.google.com/forum/#!topic/cocoapods/Lj_r08swC3o FYI https://github.com/CocoaPods/CocoaPods/issues/922 – Maxim Veksler May 15 '14 at 13:01

2 Answers2

33

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];
}
Community
  • 1
  • 1
Alexsander Akers
  • 15,967
  • 12
  • 58
  • 83
0

can you not see anything in the HTTP accept headers, if you are intercepting requests i would expect the accept header to be set to the mime of the expected type in most cases

Matt
  • 4,253
  • 1
  • 27
  • 29
  • I've thought about that, but I'd rather get it from the file than regurgitate the data, if possible. – JoBu1324 May 15 '11 at 01:31