What is the easiest and shortest way to determine the UTType
of a Data
object in Swift?
For images it can be done like this:
let imageSource = CGImageSourceCreateWithData(imageData as CFData, nil)
let imageType = CGImageSourceGetType(imageSource)
let isTypeGIF = UTTypeConformsTo(imageType, kUTTypeGIF)
But if the data type is unknown, is there a more generic approach?
Determining by the first byte does not produce an UTType
, so not the solution I am looking for:
var c = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
let firstByte = data.getBytes(c, length: 1)
let isTypeGIF = c[0] == 0x47
Update
This solution does not work, as it identifies the PNG image data as common UTI public.data
instead of public.image
or more accurately public.png
:
let imageData = UIImagePNGRepresentation(UIImage(named: "image")!)!
let url = URL(fileURLWithPath: NSTemporaryDirectory() + UUID().uuidString)
try? imageData.write(to: url, options: [.atomicWrite])
let typeIdentifer = try? url.resourceValues(forKeys: [.typeIdentifierKey])
let uti = typeIdentifer?.typeIdentifier
let isGif = UTTypeConformsTo(uti as! CFString, kUTTypeGIF)