iOS获取文件MIMEType

一、网络请求

发送网络请求,在响应头中通过response.MIMEType拿到文件的MIMEType类型
eg:NSURLConnection

- (NSString *)MIMEType:(NSURL *)url
{
    // 1.创建一个请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLResponse *response = nil;
    // 2.发送请求(返回响应)
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    // 3.获得MIMEType
    return response.MIMEType;
}

二、通过UTTypeCopyPreferredTagWithClass方法

注意:需要导入

- (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) {
        //application/octet-stream 任意的二进制数据类型
        return @"application/octet-stream";
    }
    return (__bridge NSString *)(MIMEType);
}

你可能感兴趣的:(iOS获取文件MIMEType)