NSString+MIMEType.h
#import <Foundation/Foundation.h>
@interface NSString (MIMEType)
- (NSString *)MIMEType;
- (NSString *)MIMEType2;
@end
NSString+MIMEType.m
#import "NSString+MIMEType.h"
#import <MobileCoreServices/MobileCoreServices.h>
@implementation NSString (MIMEType)
- (NSString *)MIMEType{
if (![[NSFileManager defaultManager] fileExistsAtPath:self]) {
return nil;
}
CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[self pathExtension], NULL);
CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
CFRelease(UTI);
if (!MIMEType) {
return @"application/octet-stream";
}
return (__bridge NSString *)MIMEType;
}
- (NSString *)MIMEType2{
NSURLResponse *response = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:self]];
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
return response.MIMEType;
}
@end
NSLog(@"%@", [@"/Users/zhaoyingxin/Desktop/mimetype/test.mp4" MIMEType]);
NSLog(@"%@", [@"/Users/zhaoyingxin/Desktop/mimetype/test.png" MIMEType2]);
//2016-08-07 15:59:21.326 文件的MIMEType[56270:855419] video/mp4
//2016-08-07 15:59:21.358 文件的MIMEType[56270:855419] image/png
+ (NSString *)mimeTypeForFileAtPath:(NSString *)path{
if (![[NSFileManager defaultManager] 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;
}
- (void)MIMEType{
//NSString *urlString = @"file:///Users/zhaoyingxin/Desktop/mimetype/test.mp4";
//NSURL *url = [NSURL URLWithString:urlString];
NSURL *url = [NSURL fileURLWithPath:@"/Users/zhaoyingxin/Desktop/mimetype/test.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@", response.MIMEType);
}];
NSURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSLog(@"%@", response.MIMEType);
}
NSLog(@"%@", [ViewController mimeTypeForFileAtPath:@"/Users/zhaoyingxin/Desktop/mimetype/test.png"]);
[self MIMEType];