如何在objective-c中读取MIME类型的文件

问题描述:

我有兴趣检测iPhone应用程序文档目录中文件的MIME类型。通过文档搜索没有提供任何答案。

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.

这有点hacky,但它应该工作,不知道当然,因为我只是猜测它

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

有两种选择:


  1. 如果您只需要MIME类型,请使用timeoutInterval:NSURLRequest。

  2. 如果您还想要数据,则应使用注释掉的NSURLRequest。

确保在线程中执行请求,因为它是同步的。

Make sure to perform the request in a thread though, since it's synchronous.

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"imagename" ofType:@"jpg"];
NSString* fullPath = [filePath stringByExpandingTildeInPath];
NSURL* fileUrl = [NSURL fileURLWithPath:fullPath];
//NSURLRequest* fileUrlRequest = [[NSURLRequest alloc] initWithURL:fileUrl];
NSURLRequest* fileUrlRequest = [[NSURLRequest alloc] initWithURL:fileUrl cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:.1];

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

fileData; // Ignore this if you're using the timeoutInterval
          // request, since the data will be truncated.

NSString* mimeType = [response MIMEType];

[fileUrlRequest release];