MIME type (现在称为“媒体类型(media type)”,但有时也是“内容类型(content type)”)是指示文件类型的字符串,与文件一起发送(例如,一个声音文件可能被标记为 audio/ogg ,一个图像文件可能是 image/png )。它与传统Windows上的文件扩展名有相同目的。
每一个后缀名都有一个相对应的 MIME 类型,有些后缀名可能对应多个。
常用的文件类型的 MIME type 可以查询这里:Common MIME types
import MobileCoreServices
extension String {
static func MIMEType(for pathExtension: String) -> String {
let type = "application/octet-stream"
guard let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,
pathExtension as CFString,
nil)?.takeRetainedValue() as String? else {
return type
}
if uti.hasPrefix("dyn") {
return type
}
guard let mimeType = UTTypeCopyPreferredTagWithClass(uti as CFString, kUTTagClassMIMEType)?.takeRetainedValue() as String? else {
return type
}
return mimeType
}
}
NSLog("doc: \(String.MIMEType(for: "doc"))")
NSLog("xls: \(String.MIMEType(for: "xls"))")
NSLog("ppt: \(String.MIMEType(for: "ppt"))")
NSLog("docx: \(String.MIMEType(for: "docx"))")
NSLog("xlsx: \(String.MIMEType(for: "xlsx"))")
NSLog("pptx: \(String.MIMEType(for: "pptx"))")
NSLog("md: \(String.MIMEType(for: "md"))")
NSLog("txt: \(String.MIMEType(for: "txt"))")
NSLog("rtf: \(String.MIMEType(for: "rtf"))")
输出结果:
doc: application/msword
xls: application/vnd.ms-excel
ppt: application/vnd.ms-powerpoint
docx: application/vnd.openxmlformats-officedocument.wordprocessingml.document
xlsx: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
pptx: application/vnd.openxmlformats-officedocument.presentationml.presentation
md: text/x-markdown
txt: text/plain
rtf: text/rtf
Uniform Type Identifiers
到了 iOS 14
和 macOS 11
,系统提供了全新的框架 UniformTypeIdentifiers
取代 MobileCoreServices
中提供的方法来查询 UTI。
使用起来简单了很多:
import UniformTypeIdentifiers
extension String {
static func MIMEType(for pathExtension: String) -> String {
let type = "application/octet-stream"
guard let uti = UTType(filenameExtension: pathExtension) else {
return type
}
return uti.preferredMIMEType ?? type
}
}