Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find file UTI for file, withouth pathExtension, in a path in Swift

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

like image 231
Mickey Mouse Avatar asked Feb 17 '15 20:02

Mickey Mouse


1 Answers

You can use URL method resourceValues(forKeys:) to get the file URL 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 11 • Swift 5.1

extension URL {
    var typeIdentifier: String? { (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier }
    var localizedName: String? { (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName }
}
like image 186
Leo Dabus Avatar answered Oct 22 '22 13:10

Leo Dabus