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
CodePudding user response:
A quick research on Google with "mime types hexadecimal signatures" would give you this or this, for example...
CodePudding user response:
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:
enum ImageFormat {
case gif, jpg, png, vnd, tiff, unknown
}
if let data = someData {
switch data.format() {
case .jpg, .png, .gif:
print ("Formats supported by Swift. Yihaaa")
case .tiff:
print ("Do some fancy decoding")
case .pdf:
print ("Read as a file")
case .unknown:
print ("Treat this data differently")
}
}
If you do the comparison using a String
, make sure to decode using . isoLatin1
. If you compare the bytes using the keys inside your mimeTypeSignatures
, then no need to. I only personally found it more readable to use Strings. It was helpful for decoding and to add tests.
CodePudding user response:
I've found this library:
https://github.com/sendyhalim/Swime
and it works perfectly