Created
November 14, 2018 23:38
-
-
Save Tulakshana/09029d606e092ee93189084dce1f178c to your computer and use it in GitHub Desktop.
An extension for Data to get the file extension
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
extension Data { | |
private static let mimeTypeSignatures: [UInt8 : String] = [ | |
0xFF : "image/jpeg", | |
0x89 : "image/png", | |
0x47 : "image/gif", | |
0x49 : "image/tiff", | |
0x4D : "image/tiff", | |
0x25 : "application/pdf", | |
0xD0 : "application/vnd", | |
0x46 : "text/plain", | |
] | |
var mimeType: String { | |
var c: UInt8 = 0 | |
copyBytes(to: &c, count: 1) | |
return Data.mimeTypeSignatures[c] ?? "application/octet-stream" | |
} | |
var fileExtension: String { | |
switch mimeType { | |
case "image/jpeg": | |
return "jpeg" | |
case "image/png": | |
return "png" | |
case "image/gif": | |
return "gif" | |
case "image/tiff": | |
return "tiff" | |
case "application/pdf": | |
return "pdf" | |
case "application/vnd": | |
return "vnd" | |
case "text/plain": | |
return "txt" | |
default: | |
return "uknown" | |
} | |
} | |
} |
Have you ever encountered an error like this? I have the same code as above.
Crashed: com.apple.main-thread
0 libswiftFoundation.dylib 0x118b10 Data.copyBytes(to:count:) + 340
1 My Apps 0x42432c Data.mimeType.getter + 13 (Data.swift:13)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍 what is the mimeTypeSignatures for video, audio, svg other can you please update?