-
-
Save tscholze/5df169186d6fa149fdcb to your computer and use it in GitHub Desktop.
NSData+MimeType Extension in Swift
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
// | |
// NSData+MimeType.swift | |
// Extension Playground | |
// | |
// Created by Tobias Scholze on 27.11.15. | |
// Copyright © 2015 Tobias Scholze. All rights reserved. | |
// | |
import Foundation | |
extension NSData | |
{ | |
enum MimeType | |
{ | |
case Jpeg | |
case Png | |
case Gif | |
case Mp4 | |
case Avi | |
case Ogv | |
case Webm | |
case Pdf | |
case Text | |
case Stream | |
/// Represents the ISO string value of the mime type. | |
/// E.g.: "image/jpeg" | |
var stringValue: String | |
{ | |
switch self | |
{ | |
case .Jpeg: | |
return "image/jpeg" | |
case .Png: | |
return "image/png" | |
case .Gif: | |
return "image/gif" | |
case .Mp4: | |
return "video/mp4" | |
case .Avi: | |
return "video/avi" | |
case .Ogv: | |
return "video/ogg" | |
case .Webm: | |
return "video/webm" | |
case .Pdf: | |
return "application/pdf" | |
case .Text: | |
return "text/plain" | |
case .Stream: | |
return "application/octect-stream" | |
} | |
} | |
/// Represents if the mime type is a pdf file | |
var isPdf: Bool | |
{ | |
return self == .Pdf | |
} | |
/// Represents if the mime type is an image file | |
/// Valid image file mime types: jpg, png, gif | |
var isImage: Bool | |
{ | |
let imageTypes: [MimeType] = [.Jpeg, .Png, .Gif] | |
return imageTypes.contains(self) | |
} | |
/// Represents if the mime type is an image file | |
/// Valid image file mime types: mp4, avi, ogv, webm | |
var isVideo: Bool | |
{ | |
let videoTypes: [MimeType] = [.Mp4, .Avi, .Ogv, .Webm] | |
return videoTypes.contains(self) | |
} | |
} | |
/// Returns mime type according to the first character of file stream's content | |
/// Based on: http://www.garykessler.net/library/file_sigs.html | |
var mimeType: MimeType | |
{ | |
var firstCharacter: UInt8 = 0 | |
self.getBytes(&firstCharacter, length: 1) | |
switch firstCharacter | |
{ | |
case 255: | |
return .Jpeg | |
case 137: | |
return .Png | |
case 71: | |
return .Gif | |
case 102: | |
return .Mp4 | |
case 82: | |
return .Avi | |
case 79: | |
return .Ogv | |
case 26: | |
return .Webm | |
case 37: | |
return .Pdf | |
case 70: | |
return .Text | |
default: | |
return .Stream | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment