14

我一直在尝试转换此示例中的代码(在 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)

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

4

1 回答 1

32

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

Xcode 11 • 斯威夫特 5.1

extension URL {
    var typeIdentifier: String? { (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier }
    var localizedName: String? { (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName }
}
于 2016-01-13T16:55:08.650 回答