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

1

14

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

Helprin answered 17/2, 2015 at 20:33 Comment(1)
If you look at the code you're trying to port, and the comments on the answer you're porting it from, you'll notice that it doesn't do what you need — it gets the extension from the file name, then looks up the MIME type for that extension. If you want type information without an extension, you'll need to look at the first few bytes of the file for magic numbers. iOS doesn't include an API for that, but there are third-party options.Gills
H
37

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 }
}
Helenhelena answered 13/1, 2016 at 16:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.