【问题标题】:How to find file UTI for file, withouth pathExtension, in a path in Swift如何在Swift的路径中查找文件的文件UTI,没有pathExtension
【发布时间】:2015-04-18 16:30:06
【问题描述】:

我一直在尝试转换我从example(在 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);

我的代码是这样的

    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)

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

【问题讨论】:

  • 如果您查看您尝试移植的代码,以及您要移植的答案中的 cmets,您会注意到它并不能满足您的需要——它得到了文件名中的扩展名,然后查找该扩展名的 MIME 类型。如果您想要不带扩展名的类型信息,则需要查看文件的前几个字节以查找magic numbers。 iOS 不包含用于此的 API,但 there are third-party options.

标签: ios swift swift2 uti


【解决方案1】:

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

Xcode 11 • Swift 5.1

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

【讨论】:

    猜你喜欢
    • 2014-10-19
    • 2012-02-25
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多