确定从文件加载的NSData的MIME类型 [英] Determine MIME Type of NSData Loaded From a File

查看:450
本文介绍了确定从文件加载的NSData的MIME类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

Is there an API in the iPhone-SDK to determine the mimetype of the file or NSData content?

推荐答案

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

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];
}

这篇关于确定从文件加载的NSData的MIME类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆