Swift: How to determine file type
Using Uniform Type Identifiers (UTIs)
Recently I had to determine what type a given file was for my macOS app Media Explorer. For example, is it an image? a video? or a document? An easy way to do this is by using Uniform Type Identifiers.
A UTI is an identifier that a given extension can fall under to help identify it’s class or type of item. There are broad UTIs such as public.image, and more precise UTIs such as com.apple.quicktime-movie.
We can use these to group together files of a certain type or to identify a certain type of file we are interested in.
First extract the file extension. Given a path, you can do this easily with NSURL:
let extension = NSURL(fileURLWithPath: filePath).pathExtension
Next, convert this into a UTI:
let uti = UTTypeCreatePreferredIdentifierForTag(
kUTTagClassFilenameExtension,
extension!,
nil)
Finally, put this UTI to good use:
if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeImage) {
print("This is an image!")
}
You can find a list of UTIs at the Mac Developer Library.