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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM