ios - 如何在没有 pathExtension 的情况下在 Swift 的路径中查找文件的文件 UTI

标签 ios swift swift2 uti

我一直在尝试转换我从这个 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)

我想做的就是找出一个文件是图片还是视频文件

最佳答案

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

Xcode 11 • Swift 5.1

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

关于ios - 如何在没有 pathExtension 的情况下在 Swift 的路径中查找文件的文件 UTI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28570627/

相关文章:

ios - swift 3 : Pass String from TableViewController to another TableViewController

Swift - 如何使用对象数组对表进行分组

swift - 我怎样才能等到下载完成?

Iphone 4s 和 Iphone 5s 上的 Swift TableView 高度不同

ios - RxSwift - 无法推断通用参数 'Self'

Swift:guard let 与 if let

ios - 从 Parse 检索对象时无法正确重新加载数据

ios - AVSpeech合成器: AVSpeechSynthesisIPANotationAttribute seems like does not support Chinese

ios - 在 Mac 上自动构建 Unity iOS

ios - 如何在 swift 中使用 FMDB 以异步模式插入数据?