Get image file type programmatically in swift

You have to get the first byte of your image in binary. This byte indicate which kind of image type. Here is the code that I've used for my project but in Objective-c:

uint8_t c;
        [_receivedData getBytes:&c length:1];

        NSString *extension = @"jpg";

        switch (c) {
            case 0xFF:
            {
                extension = @"jpg";
            }
            case 0x89:
            {
                extension = @"png";
            }
                break;
            case 0x47:
            {
                extension = @"gif";
            }
                break;
            case 0x49:
            case 0x4D:
            {
                extension = @"tiff";
            }
                break;
            default:
                FLog(@"unknown image type");
        }

Try with this in swift (1.2, else you have to use var ext):

func imageType(imgData : NSData) -> String
{
    var c = [UInt8](count: 1, repeatedValue: 0)
    imgData.getBytes(&c, length: 1)

    let ext : String

    switch (c[0]) {
    case 0xFF:

        ext = "jpg"

    case 0x89:

        ext = "png"
    case 0x47:

        ext = "gif"
    case 0x49, 0x4D :
        ext = "tiff"
    default:
        ext = "" //unknown
    }

    return ext
}

Update for Swift 3.0.2

Based on Hoa's answer and Kingfisher library

import UIKit
import ImageIO

struct ImageHeaderData{
    static var PNG: [UInt8] = [0x89]
    static var JPEG: [UInt8] = [0xFF]
    static var GIF: [UInt8] = [0x47]
    static var TIFF_01: [UInt8] = [0x49]
    static var TIFF_02: [UInt8] = [0x4D]
}

enum ImageFormat{
    case Unknown, PNG, JPEG, GIF, TIFF
}


extension NSData{
    var imageFormat: ImageFormat{
        var buffer = [UInt8](repeating: 0, count: 1)
        self.getBytes(&buffer, range: NSRange(location: 0,length: 1))
        if buffer == ImageHeaderData.PNG
        {
            return .PNG
        } else if buffer == ImageHeaderData.JPEG
        {
            return .JPEG
        } else if buffer == ImageHeaderData.GIF
        {
            return .GIF
        } else if buffer == ImageHeaderData.TIFF_01 || buffer == ImageHeaderData.TIFF_02{
            return .TIFF
        } else{
            return .Unknown
        }
    }
}

Usage

let imageURLFromParse = NSURL(string : "https://i.stack.imgur.com/R64uj.jpg")
let imageData = NSData(contentsOf: imageURLFromParse! as URL)
print(imageData!.imageFormat)

You can use this with Both local and online images.