从NSData确定MIME类型? [英] Determine MIME type from NSData?
问题描述
您如何确定NSData对象的mime类型?我打算让用户从iPhone上上传视频/图片,并将该文件包装在NSData类中.
How would you determine the mime type for an NSData object? I plan to have the user to upload a video/picture from their iPhone and have that file be wrapped in a NSData class.
我想知道是否可以从NSData中分辨出哑剧类型.这个问题只有几个答案,最近的一个是2010年(4年前!).谢谢!
I was wondering if I can tell the mime type from the NSData. There are only a few answers to this question and the most recent one is from 2010 (4 years ago!). Thanks!
NSData *data; // can be an image or video
NSString *mimeType = [data getMimetype]; // how would I implement getMimeType
推荐答案
基于 ml来自类似帖子的答案,我为NSData添加了mime类型确定:
Based on ml's answer from a similar post, I've added the mime types determination for NSData:
ObjC:
+ (NSString *)mimeTypeForData:(NSData *)data {
uint8_t c;
[data getBytes:&c length:1];
switch (c) {
case 0xFF:
return @"image/jpeg";
break;
case 0x89:
return @"image/png";
break;
case 0x47:
return @"image/gif";
break;
case 0x49:
case 0x4D:
return @"image/tiff";
break;
case 0x25:
return @"application/pdf";
break;
case 0xD0:
return @"application/vnd";
break;
case 0x46:
return @"text/plain";
break;
default:
return @"application/octet-stream";
}
return nil;
}
迅速:
static func mimeType(for data: Data) -> String {
var b: UInt8 = 0
data.copyBytes(to: &b, count: 1)
switch b {
case 0xFF:
return "image/jpeg"
case 0x89:
return "image/png"
case 0x47:
return "image/gif"
case 0x4D, 0x49:
return "image/tiff"
case 0x25:
return "application/pdf"
case 0xD0:
return "application/vnd"
case 0x46:
return "text/plain"
default:
return "application/octet-stream"
}
}
此文件仅处理主要文件类型,但您可以根据需要完成它:所有文件签名均可用这里,只需使用与我相同的模式即可.
This handle main file types only, but you can complete it to fit your needs: all the files signature are available here, just use the same pattern as I did.
PS:所有相应的哑剧类型都可以在此处使用
PS: all the corresponding mime types are available here
这篇关于从NSData确定MIME类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!