How to find the UTI file for a file with the pathExtension node in the path in Swift

I tried 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 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

  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 the file is an image or a video file

+5
source share
1 answer

You can use the resourceValues(forKeys:) URL method to get a URL TypeIdentifierKey file that returns a uniform file type identifier (UTI). You just need to check if the return value is "com.apple.m4v-video" for video, "public.jpeg" or "public.png" for images, etc. You can add the extension of the typeIdentifier property to the URL to return the string value of TypeIdentifierKey as follows:

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 } } 
+10
source

Source: https://habr.com/ru/post/1213563/


All Articles