I'm trying to convert this deprecated bit of code into its iOS 16 compatible form:
extension URL {
public static func pathExtensionForUTI(_ uti: String) -> String? {
return UTTypeCopyPreferredTagWithClass(uti as CFString, kUTTagClassFilenameExtension)?.takeRetainedValue() as String?
}
}
This is a static method on URL that returns an optional path extension string for the UTI, which is passed into the method from elsewhere.
I thought the solution would be something like this, using preferredFilenameExtension to get the path extension:
public static func pathExtensionForUTI(_ uti: String) -> String? {
return UTType(filenameExtension: uti)?.preferredFilenameExtension
}
However, this doesn't work as expected and I am pretty sure that it is returning a nil value since the operation cancels itself. I'm unable to trigger a breakpoint to verify this since the method is called from outside the app (e.g., sharing a photo from the Photos app).
I've also tried:
public func pathExtensionForUTI(_ uti: String) -> String? {
return UTType(filenameExtension: self.pathExtension)?.preferredFilenameExtension
}
But this requires turning the static method into an instance method and creating several URL objects. It also doesn't take into account the passed-in uti.
Thanks in advance for any insight you can provide!
Your code returns the preferred path extension for a string identifier like public.jpeg
. This is pretty easy with UTType
, you have to use the init
method taking an identifier
import UniformTypeIdentifiers
func pathExtensionForUTI(_ identifier: String) -> String? {
UTType(identifier)?.preferredFilenameExtension
}
pathExtensionForUTI("public.jpeg")
I would put the code into an extension of UTType
rather than URL