Skip to content

Instantly share code, notes, and snippets.

@aaadonai
Created April 19, 2016 01:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aaadonai/962e6bbc7958f9a24f180f7daa654f13 to your computer and use it in GitHub Desktop.
Save aaadonai/962e6bbc7958f9a24f180f7daa654f13 to your computer and use it in GitHub Desktop.
A Swift enum that recognizes basic mimetypes in a NSData
// 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