确定从文件加载的NSData的MIME类型

JoB*_*324 17 iphone objective-c nsdata mime-types

出于各种原因,我使用NSURLProtocol拦截http请求并从我的应用程序文档目录中的文件加载内容.部分过程涉及加载NSData对象,该对象可以是从html文件到jpeg图像的任何内容.NSURLProtocol需要设置mimetype.

iPhone-SDK中是否有API来确定文件或NSData内容的mimetype?

Ale*_*ers 32

也许您可以下载该文件并使用来获取文件的MIME类型.

+ (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];
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*att 0

你在 HTTP 接受标头中看不到任何内容吗?如果你拦截请求,我希望在大多数情况下将接受标头设置为预期类型的​​ mime