iOS开发之网络编程--获取文件的MIMEType

前言:有时候我们需要获取文件的MIMEType的信息,下面就介绍关于获取MIMEType的方法。

1、直接百度搜索关键字"MIMEType",你会找到,然后查吧:

2、用代码获取文件的MIMEType信息:

 1 #import "GetMIMEType.h"
 2 
 3 #import <MobileCoreServices/MobileCoreServices.h>
 4 
 5 @implementation GetMIMEType
 6 
 7 #pragma mark - 类方法
 8 + (NSString*)getMIMETypeURLRequestAtFilePath:(NSString*)path{
 9     return [[[GetMIMEType alloc] init] getMIMETypeURLRequestAtPath:path];
10 }
11 
12 + (NSString *)getMIMETypeWithCAPIAtFilePath:(NSString *)path{
13     return [[[GetMIMEType alloc] init] getMIMETypeWithCAPIAtFilePath:path];
14 }
15 #pragma mark - 对象方法
16 //向该文件发送请求,根据请求头拿到该文件的MIMEType
17 -(NSString *)getMIMETypeURLRequestAtPath:(NSString*)path
18 {
19     //1.确定请求路径
20     NSURL *url = [NSURL fileURLWithPath:path];
21     
22     //2.创建可变的请求对象
23     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
24     
25     //3.发送请求
26     NSHTTPURLResponse *response = nil;
27     [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
28     
29     NSString *mimeType = response.MIMEType;
30     return mimeType;
31 }
32 
33 //调用C语言的API来获得文件的MIMEType ,只能获取本地文件哦,无法获取网络请求来的文件
34 -(NSString *)getMIMETypeWithCAPIAtFilePath:(NSString *)path
35 {
36     if (![[[NSFileManager alloc] init] fileExistsAtPath:path]) {
37         return nil;
38     }
39     
40     CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[path pathExtension], NULL);
41     CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
42     CFRelease(UTI);
43     if (!MIMEType) {
44         return @"application/octet-stream";
45     }
46     return (__bridge NSString *)(MIMEType)
47     ;
48 }
49 
50 @end

运行:

github源码下载:https://github.com/HeYang123456789/GetMIMEType

原文地址:https://www.cnblogs.com/goodboy-heyang/p/5193741.html