How to find file UTI for file, withouth pathExtens

2019-01-09 11:04发布

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

1条回答
对你真心纯属浪费
2楼-- · 2019-01-09 11: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 9 • Swift 4 or Xcode 8.3.2 • Swift 3.1

extension URL {
    var typeIdentifier: String? {
        return (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier
    }
    var localizedName: String? {
        return (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName
    }
}
查看更多
登录 后发表回答