views:

907

answers:

3

I am interested in detecting the MIME-type for a file in the documents directory of my iPhone application. A search through the docs did not provide any answers.

+1  A: 

On Mac OS X this would be handled through LaunchServices and UTIs. On the iPhone these are not available. Since the only way for data to get into your sandbox is for you to put it there, most apps have intrinsic knowledge about the data of any file they can read.

If you have a need for such a feature you should file a feature request with Apple.

Louis Gerbarg
this is an upload from a user into the app. I am using cocoaHTTPServer to allow a file upload via web-browser into the device. I want to check that the file is of the right type before working with it on the device.
coneybeare
Sure, I figured as much. What I am saying is that it is a very atypical need compared to an OS where files come and go independent of apps, so it is not suprising there is little support for it.
Louis Gerbarg
A: 

I'm not sure what are the practices on iPhone, but if you're allowed to, I'd make use of UNIX philosophy here: use program file, which is the standard way to detect filetype on an UNIX operating system. It includes a vast database of magic markers for filetype detection. Since file is probably not shipped on iPhone, you could include it in your app bundle. There might be a library implementing file's functionality.

Alternatively, you could trust the browser. Browsers send the MIME type they guessed somewhere in the HTTP headers. I know that I can easily grab the MIME type information in PHP. That of course depends if you're willing to trust the client.

Ivan Vučica
You cannot spawn processes on the iPhone, fork() is not allowed in sandboxed apps, so using file is not viable. Also, I assume you mean trust the server, not the browser. A http server sends the mimetype of a file. That may be viable if he is getting the files from an http server, which is not clear.
Louis Gerbarg
Actually he mentioned he is running an http server in the app in a comment. Depending on how the file is being sent the mimetype may or may not be transmitted.
Louis Gerbarg
+3  A: 

It's a bit hacky, but it should work, don't know for sure because I'm just guessing at it

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"imagename" ofType:@"jpg"];
NSString* fullPath = [filePath stringByExpandingTildeInPath];
NSURL* fileUrl = [NSURL fileURLWithPath:fullPath];
NSURLRequest* fileUrlRequest = [NSURLRequest requestWithUrl:fileUrl];

NSError* error = nil;
NSURLResopnse* response = nil;
NSData* fileData = [NSURLConnection sendSynchronousRequest:fileUrlRequest returningResponse:&response error:&error];

NSString* mimeType = [response MIMEType];
slf