Skip to content

Instantly share code, notes, and snippets.

@Tulakshana
Created November 14, 2018 23:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tulakshana/09029d606e092ee93189084dce1f178c to your computer and use it in GitHub Desktop.
Save Tulakshana/09029d606e092ee93189084dce1f178c to your computer and use it in GitHub Desktop.
An extension for Data to get the file extension
extension Data {
private static let mimeTypeSignatures: [UInt8 : String] = [
0xFF : "image/jpeg",
0x89 : "image/png",
0x47 : "image/gif",
0x49 : "image/tiff",
0x4D : "image/tiff",
0x25 : "application/pdf",
0xD0 : "application/vnd",
0x46 : "text/plain",
]
var mimeType: String {
var c: UInt8 = 0
copyBytes(to: &c, count: 1)
return Data.mimeTypeSignatures[c] ?? "application/octet-stream"
}
var fileExtension: String {
switch mimeType {
case "image/jpeg":
return "jpeg"
case "image/png":
return "png"
case "image/gif":
return "gif"
case "image/tiff":
return "tiff"
case "application/pdf":
return "pdf"
case "application/vnd":
return "vnd"
case "text/plain":
return "txt"
default:
return "uknown"
}
}
}
@awaismubeen
Copy link

👍 what is the mimeTypeSignatures for video, audio, svg other can you please update?

@adeds
Copy link

adeds commented Oct 17, 2023

Have you ever encountered an error like this? I have the same code as above.

Crashed: com.apple.main-thread
0  libswiftFoundation.dylib       0x118b10 Data.copyBytes(to:count:) + 340
1  My Apps                        0x42432c Data.mimeType.getter + 13 (Data.swift:13)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment