• 2 min read
Getting the content type of local files
To get the content type of a local file from a URL, we can use the resourceValues(forKeys:)
method of the URL type. This method fetches a collection of values about the resource it refers to. For files, these values can provide the content type, creation or modification date, whether it’s a directory or not, and more. To fetch the content type, you need to provide the contentTypeKey
value to this method.
let contentType = try url.resourceValues(forKeys: [.contentTypeKey]).contentType
The value returned by the contentType
property is an UTType
structure, introduced in macOS 11.0 and iOS 14.0 as part of the UniformTypeIdentifiers
framework.
Checking conformance to related types based on the extracted content type
You may want to know whether a file is an image, audio, movie, or any other general type, regardless of its format.
let url = URL(fileURLWithPath: "path/to/local/file")
guard let contentType = try url.resourceValues(forKeys: [.contentTypeKey]).contentType else {
return
}
if contentType.conforms(to: .image) {
print("Image file")
} else if contentType.conforms(to: .movie) {
print("Video file")
} else if scontentType.conforms(to: .audio) {
print("Audio file")
} else {
print("Unknown file")
}
Note that it’s necessary to import the UniformTypeIdentifiers
framework to make the UTType
available in a source file, but it’s not necessary if you don’t plan to explicitly declare it.