The file type is detected by checking signature bytes and, for some container formats, scanning the full file contents when required.
This is swift port of file-type
Documentation: Swift Package Index DocC
- Swift 6.2+
- Xcode 26.3+ or another Swift 6.2-compatible toolchain
import PackageDescription
let package = Package(
name: "MyApp",
dependencies: [
.package(url: "https://github.com/velocityzen/FileType", branch: "main")
]
)If you are consuming a tagged release instead of main, use the latest Swift 6.2-compatible tag.
Inspect mime type
import FileType
let path = "/path/to/some-file.jpg"
let url = URL(fileURLWithPath: path, isDirectory: false)
let fileType = try FileType.detect(contentsOf: url)
fileType?.type == .jpg // true
fileType // FileType(type: .jpg, ext: "jpg", mime: "image/jpeg")Limit detection to MIME major groups when you already know the broad file family:
import FileType
let data = try Data(contentsOf: url)
let imageType = FileType.detect(in: data, matching: .image)
imageType?.mimeGroup == .image // trueInspect the detection requirement before sampling file contents:
import FileType
switch FileType.dataRequirement(for: .docx) {
case let .prefix(byteCount):
// Read only the prefix for simple signatures.
print(byteCount)
case .fullFile:
// Container formats like DOCX require the full file.
print("Read the full file")
}returns all file types and mime information
returns all file types whose mime begins with that major type
returns file type detected by checking the magic number
limits detection to a MIME major group such as .image, .audio, or .video
detects the type from a file URL and only loads the full file when a detector requires it
limits URL-based detection to one MIME major group
detects the type from a file handle positioned at the start of the file
limits file-handle detection to one MIME major group
returns the minimum prefix size used by the detector for that type
returns the minimum prefix size needed for that MIME major group
returns whether the detector can work from a prefix or requires the full file
returns whether that MIME major group can work from a prefix or requires the full file
returns the canonical on-disk extension for a public file type case
returns the first component of the detected MIME type
On Apple platforms with UniformTypeIdentifiers available (macOS 11+, iOS 14+, tvOS 14+, watchOS 7+, visionOS 1+), you can detect file types from UTI identifiers:
import FileType
// From a UTI identifier string
let fileType = FileType.detect(uti: "public.jpeg")
fileType?.type == .jpg // trueimport FileType
import UniformTypeIdentifiers
// From a UTType value
let fileType = FileType.detect(utType: .png)
fileType?.type == .png // trueresolves a UTI identifier string to a file type using the system's UTType mapping
resolves a UTType value to a file type using its MIME type and file extension
getFor(...) and getBytesCountFor(...) remain as deprecated wrappers for older callers.
3g2- Multimedia container format defined by the 3GPP2 for 3G CDMA2000 multimedia services3gp- Multimedia container format defined by the Third Generation Partnership Project (3GPP) for 3G UMTS multimedia services3mf- 3D Manufacturing Format7zaac- Advanced Audio Codingac3- ATSC A/52 Audio Fileaceai- Adobe Illustrator Artworkaifalias- macOS Alias fileamrape- Monkey's Audioapkapng— image details - Animated Portable Network Graphicsararjarrow- Columnar format for tables of dataarw— image details - Sony Alpha Raw image fileasar- Simple extensive tar-like archive format with indexingasf- Advanced Systems Formataviavif— image details - AV1 Image File Formatavroblendbmp— image detailsbpg— image detailsbz2cabcfbchm- Microsoft Compiled HTML Helpcpiocr2- Canon Raw image file (v2) — image detailscr3- Canon Raw image file (v3) — image detailscrxcur— image detailsdat- Windows Registry hivedcm— image details - DICOM Image Filedebdmgdng— image details - Adobe Digital Negative image filedocmdocxdotmdotxdrcdwgdsf- Sony DSD Stream File (DSF)elf- Unix Executable and Linkable Formateoteps- Encapsulated PostScriptepubexef4a- Audio-only ISO base media file format used by Adobe Flash Playerf4b- Audiobook and podcast ISO base media file format used by Adobe Flash Playerf4p- ISO base media file format protected by Adobe Access DRM used by Adobe Flash Playerf4v- ISO base media file format used by Adobe Flash Playerfbxflacflif— image detailsflvgif— image detailsglb- GL Transmission Formatgzheic— image detailsiccicns— image detailsico— image detailsics- iCalendarism- Microsoft Smooth Streaming manifestinddit- Audio module format: Impulse Trackerj2c— image details - JPEG 2000 codestreamjarjp2— image details - JPEG 2000jpg— image detailsjls— image detailsjmp- JMP data filejpm— image details - JPEG 2000jpx— image details - JPEG 2000jxl— image details - JPEG XL image formatjxr— image detailsktx— image detailslnk- Microsoft Windows file shortcutlzlz4lzh- LZH archivem3u- HLS playlist when HLS-specific#EXT-X-tags are presentm4a- Audio-only MPEG-4 filesm4b- Audiobook and podcast MPEG-4 files, which also contain metadata including chapter markers, images, and hyperlinksm4p- MPEG-4 files with audio streams encrypted by FairPlay Digital Rights Management as were sold through the iTunes Storem4v- MPEG-4 Visual bitstreamsmachomidmie- Dedicated meta information format which supports storage of binary as well as textual meta informationmj2- Motion JPEG 2000mkvmobi- Mobipocketmovmp1- MPEG-1 Audio Layer Imp2mp3mp4mpd- MPEG-DASH manifestmpc- Musepack (SV7 & SV8)mpgmts- MPEG-2 Transport Stream, both raw and Blu-ray Disc Audio-Video (BDAV) versionsmxfnef— image details - Nikon Electronic Format image filenesodg- OpenDocument graphicsodp- OpenDocument for presentationsods- OpenDocument for spreadsheetsodt- OpenDocument for word processingogaoggogmogvogxopusorf— image details - Olympus Raw image fileotfotg- OpenDocument graphics templateotp- OpenDocument presentation templateots- OpenDocument spreadsheet templateott- OpenDocument text templateparquetpcap- Libpcap File Formatpdfpgp- Pretty Good Privacypng— image detailsppsmppsxpotmpotxpptmpptxpspsd— image detailspstqcpraf— image details - Fujifilm RAW image filerarreg- Windows Registry exportrmrpmrtfrw2— image details - Panasonic RAW image files3m- Audio module format: ScreamTracker 3sav- SPSS data fileshp- Geospatial vector data formatskp- SketchUpspxsqlitestl- Standard Tesselated Geometry File Format (ASCII only)swftartif— image detailsttc- TrueType Collectionttfvcf- vCardvoc- Creative Voice Filevsdxvttwasmwavwebmwebp— image detailswoff2woffwv- WavPackxcf— image details - eXperimental Computing Facilityxlsmxlsxxltmxltxxm- Audio module format: FastTracker 2xmlxpixzZzipzst- Archive file
Pull requests are welcome for additional commonly used file types.
swift test