I've been trying to convert this code which I had from this example (in Objective-c) with no luck.
String *path; // contains the file path
// Get the UTI from the file's extension:
CFStringRef pathExtension = (__bridge_retained CFStringRef)[path pathExtension];
CFStringRef type = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, NULL);
CFRelease(pathExtension);
// The UTI can be converted to a mime type:
NSString *mimeType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass(type, kUTTagClassMIMEType);
if (type != NULL)
CFRelease(type);
My code is this
import MobileCoreServices
let path: String?
let pathExt = path.pathExtension as CFStringRef
let type = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, NULL);
let mimeType = UTTypeCopyPreferredTagWithClass(type, kUTTagClassMIMEType)
if type != Null
CFRelease(type)
All I want to do is find out if a file is an image or a video file
You can use
URL
methodresourceValues(forKeys:)
to get the fileURL TypeIdentifierKey
which returns the file uniform type identifier (UTI). You just need to check if the returned value is "com.apple.m4v-video" for videos, "public.jpeg" or "public.png" for images and so on. You can add a typeIdentifier property extension to URL to return the TypeIdentifierKey string value as follow:Xcode 9 • Swift 4 or Xcode 8.3.2 • Swift 3.1