Created
April 19, 2016 01:02
-
-
Save aaadonai/962e6bbc7958f9a24f180f7daa654f13 to your computer and use it in GitHub Desktop.
A Swift enum that recognizes basic mimetypes in a NSData
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
// Inspired by: http://stackoverflow.com/questions/4147311/finding-image-type-from-nsdata-or-uiimage/5042365#5042365 | |
import Foundation | |
enum DocumentType: String { | |
case jpeg = "image/jpeg" | |
case png = "image/png" | |
case gif = "image/gif" | |
case tiff = "image/tiff" | |
case pdf = "application/pdf" | |
case vnd = "application/vnd" | |
case plainText = "text/plain" | |
case anyBinary = "application/octet-stream" | |
func mimeType(data: NSData) -> DocumentType { | |
var firstByte: __uint8_t = 0x00 | |
data.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 0xD0: | |
return .vnd | |
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