如何在Swift中的路径中找到文件UTI for file,withouth pathExtension

Mic*_*use 8 uti ios swift swift2

我一直试图转换这个代码,我从这个例子(在Objective-c中)没有运气.

    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);
Run Code Online (Sandbox Code Playgroud)

我的代码是这样的

    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)
Run Code Online (Sandbox Code Playgroud)

我想要做的就是找出文件是图像还是视频文件

Leo*_*bus 19

您可以使用URL方法resourceValues(forKeys:)获取URL TypeIdentifierKey返回文件统一类型标识符(UTI)的文件.您只需要检查返回的值是视频的"com.apple.m4v-video",图像的"public.jpeg"或"public.png"等等.您可以向URL添加typeIdentifier属性扩展以返回TypeIdentifierKey字符串值,如下所示:

Xcode 9•Swift 4Xcode 8.3.2•Swift 3.1

extension URL {
    var typeIdentifier: String? { (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier }
    var localizedName: String? { (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName }
}
Run Code Online (Sandbox Code Playgroud)