Created
November 14, 2018 23:38
-
-
Save Tulakshana/09029d606e092ee93189084dce1f178c to your computer and use it in GitHub Desktop.
An extension for Data to get the file extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have you ever encountered an error like this? I have the same code as above.