Table of contents

Get a file mime type in Objective C

Objective C Feb 15, 2020 Viewed 143 Comments 0

To upload a file using http post, we need to pass the file resource type to the server, so that the server can determine whether the file is a picture, audio, or video. This article is about using Objective C under the iOS project to get the MIME Type (Content Type) of a file based on the extension type of the file name.


RequiresMobileCoreServices.framework. Add the framework toBuild Phases -> Link Binary With Libraries, and include the MobileCoreServices framework.

#import <MobileCoreServices/MobileCoreServices.h>

 Get mime type
- (NSString *)getMimeType:(NSString *)fileExtension{
  NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtension, NULL);
  NSString *mimeType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
  return mimeType;

Use it

NSString *path = @"/home/test.png";
NSString *fileExtension = [path pathExtension];
NSString *contentType = [self getMimeType:fileExtension];
NSLog(@"%@", contentType);
// Output  image/png


What you get with this method is not the true MIME-Type of the file. For example, a picture is png and the MIME Type isimage/png. If the extension of this picture is changed to jpg, you will get image/jpeg.

Updated Mar 18, 2020