1. 程式人生 > >iOS-網路-如何獲取檔案的MINEType

iOS-網路-如何獲取檔案的MINEType

//  ViewController.m

#import "ViewController.h"

#import <MobileCoreServices/MobileCoreServices.h>

@interface ViewController ()

@end

@implementation ViewController

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //1.傳送請求,可以響應頭(內部有MIMEType)
    //2.百度
    //3.呼叫C語言的API
    //4.application/octet-stream 任意的二進位制資料型別
    
    //[self getMimeType];
   NSString *mimeType= [self mimeTypeForFileAtPath:@"/Users/xiaomage/Desktop/123.h"];
    NSLog(@"%@",mimeType);
}

-(void)getMimeType
{
    
    //1.url
    NSURL *url = [NSURL fileURLWithPath:@"/Users/xiaomage/Desktop/123.h"];
    
    //2.建立請求物件
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //3.傳送非同步請求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
       
        //4.獲得檔案的型別
        NSLog(@"%@",response.MIMEType);
    }];
    
}

- (NSString *)mimeTypeForFileAtPath:(NSString *)path
{
    if (![[[NSFileManager alloc] init] fileExistsAtPath:path]) {
        return nil;
    }
    
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[path pathExtension], NULL);
    CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
    CFRelease(UTI);
    if (!MIMEType) {
        return @"application/octet-stream";
    }
    return (__bridge NSString *)(MIMEType);
}
@end