获得文件的MIMEType

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//    NSString *str = [self getMIMEType];
//    NSLog(@"%@",str);
//
    NSString *str = [self mimeTypeForFileAtPath:@"/Users/xmg/Desktop/122.mp4"];
    NSLog(@"%@",str);
    
}
//向该文件发送请求,根据请求头拿到该文件的MIMEType
-(NSString *)getMIMEType
{
    //1.确定请求路径
    NSURL *url = [NSURL fileURLWithPath:@"/Users/xmg/Desktop/122.mp4"];
    
    //2.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //3.发送请求
    NSHTTPURLResponse *response = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    
    NSString *mimeType = response.MIMEType;
    return mimeType;
}
//调用C语言的API来获得文件的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)
    ;
}

//可以直接百度

注意:用C语言API获得文件的MIMEType要导入系统库

posted @ 2017-03-20 22:20  漫天要价  阅读(288)  评论(0编辑  收藏  举报