如何在Swift中的路径中找到文件UTI for file,withouth pathExtension [英] How to find file UTI for file, withouth pathExtension, in a path in Swift
问题描述
我一直试图将此代码转换为示例(在Objective-c中)没有运气。
I've been trying 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'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)
我想要做的就是找出文件是图像还是视频文件
All I want to do is find out if a file is an image or a video file
推荐答案
您可以使用 URL
方法 resourceValues(forKeys :)
来获取文件 URL TypeIdentifierKey
返回文件统一类型标识符(UTI)。您只需要检查返回的值是视频的com.apple.m4v-video,图像的public.jpeg或public.png等等。您可以向URL添加typeIdentifier属性扩展以返回TypeIdentifierKey字符串值,如下所示:
You can use URL
method resourceValues(forKeys:)
to get the file URL TypeIdentifierKey
which returns the file uniform type identifier (UTI). You just need to check if the returned value is "com.apple.m4v-video" for videos, "public.jpeg" or "public.png" for images and so on. You can add a typeIdentifier property extension to URL to return the TypeIdentifierKey string value as follow:
Xcode 9•Swift 4 或 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
}
}
这篇关于如何在Swift中的路径中找到文件UTI for file,withouth pathExtension的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!