Created
July 14, 2022 19:26
-
-
Save lucasfeijo/6825a1f70c436a0422504bcfc181fa38 to your computer and use it in GitHub Desktop.
Get MIME type from Swift Data
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
public enum MIMEType: String { | |
case jpeg = "image/jpeg" | |
case png = "image/png" | |
case gif = "image/gif" | |
case tiff = "image/tiff" | |
case pdf = "application/pdf" | |
case plainText = "text/plain" | |
case anyBinary = "application/octet-stream" | |
} | |
public extension Data { | |
var mimeType: MIMEType { | |
var firstByte: __uint8_t = 0x00 | |
NSData(data: self).getBytes(&firstByte, length: 1) | |
switch firstByte { | |
case 0xFF: | |
return .jpeg | |
case 0x89: | |
return .png | |
case 0x47: | |
return .gif | |
case 0x49, 0x4D: | |
return .tiff | |
case 0x25: | |
return .pdf | |
case 0x46: | |
return .plainText | |
default: | |
return .anyBinary | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment