Dealing with file extensions and Uniform Type Identifiers
There are different ways of representing a type of file, two popular ones being file extensions and another being Uniform Type Identifiers (UTIs) from the UIKit APIs. When working with a UIKit API such as UIDocumentPickerViewController
we may need to distinguish between these types.
We can create independent types to hold file extensions and type identifiers, this makes it really clear which one is required for a particular piece of functionality.
struct FileExtension {
let rawValue: String
func asTypeIdentifier() -> TypeIdentifier {
let identifierCreated = UTTypeCreatePreferredIdentifierForTag(
kUTTagClassFilenameExtension, rawValue as NSString, nil
)
if let typeIdentifier = identifierCreated?.takeRetainedValue() {
return TypeIdentifier(rawValue: typeIdentifier as String)
}
return TypeIdentifier(rawValue: "public.data")
}
}
struct TypeIdentifier {
let rawValue: String
}
I hope the article was useful. If you have any feedback or questions please feel free to reach out to me on Twitter.
Thanks for reading and happy coding!
Hi, I hope you enjoyed the article. I am Andrew - a builder of apps and developer tools. Articles on the blog focus on all aspects of Android and iOS development using Kotlin and Swift.
Subscribe via RSS
Want to read more?
Here are some other articles you may enjoy.