This tool detects a file’s MIME type using magic bytes and can retrieve the file extension based on the MIME type.
It can identify the MIME type of Data
, based on Swime and ported from file-type.
The Extensions
, mimeTypes
, and mimeTypesAll
data in the dependency package are all generated by scripts based on file-type.
The function for checking whether the bytes match the MimeType
specification is generated from a mapping.js
mapping file created using data from the file-type
package.
Since the data may not always be accurate, it can be corrected by modifying the mapping.js
file.
Add CodeMirror to your project using Xcode:
- In Xcode, go to
File
→Add Package Dependencies...
- Enter the repository URL:
https://github.com/jaywcjlove/FileType.git
- Click
Add Package
Or add it to your Package.swift
file:
dependencies: [
.package(url: "https://github.com/jaywcjlove/FileType.git", from: "1.0.0")
]
Inspect mime type
import FileType
let path = "/path/to/some-file.jpg"
let url = URL(fileURLWithPath: path, isDirectory: false)
let data = try! Data(contentsOf: url)
let mimeType = FileType.mimeType(data: data)
mimeType?.type == .jpg // true
mimeType! // MimeType(mime: "image/jpeg", ext: "jpg", type: .jpg)
Get the file extension from a MIME type
let avroMimeType = MimeType.mimeTypesAll.first { $0.mime == "application/avro" }
if let avroMimeType = avroMimeType {
avroMimeType.mime // "application/avro"
avroMimeType.type // .avro
avroMimeType.type.rawValue // "avro"
}
let mimeTypes = MimeType.mimeTypes.first(where: { $0.key == "application/mp4" })
if let mimeTypes = mimeTypes {
mimeTypes.compressible
mimeTypes.extensions // ["mp4","mpg4","mp4s","m4p"]
}
Thanks to these projects:
- https://github.com/sendyhalim/Swime
- https://github.com/sindresorhus/file-type
- https://github.com/jshttp/mime-db
Licensed under the MIT License.