I’m using the PhotosPicker library to select either an image or a video and put it into data:
@State private var selectedImageData: Data? = nil
and I need to find out what exactly was selected.
All the answers I’ve found was about how to retrieve the meme type from a file using the path, but I don’t get the file path using PhotosPicker.
I’ve found this somewhere:
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"
}
}
and it works but it’s incomplete, I also need mp4, mov and just as many as possible
2
Answers
A quick research on Google with "mime types hexadecimal signatures" would give you this or this, for example…
EDIT
The array of signatures in your code reads the first byte of data of the file to determine its type.
Here is the example code of what I am saying :
It converts the 10 first bytes of the data to an array, then checks for each MIME type if the array starts with the MIME type bytes. (You will need to take more than ten bytes if MIME signatures are more than 10 bytes long).
You can use the Signature re-using the code here
After copy-pasting the logic and adding the cases for tiff, vnd or text/plain, you will end up with this logic:
If you do the comparison using a
String
, make sure to decode using. isoLatin1
. If you compare the bytes using the keys inside yourmimeTypeSignatures
, then no need to. I only personally found it more readable to use Strings. It was helpful for decoding and to add tests.