Getting extensions of a given UTType
Asked Answered
F

2

11

I know I can get the UTType of a given extension using UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension, NULL) but I can't find a way to do the opposite, that is an array of extensions for a given UT... What can I do?

Thank you

Faludi answered 10/5, 2012 at 17:12 Comment(0)
A
11

UTTypeCopyPreferredTagWithClass is used to convert a UTI to another tag, like file extensions:

NSString *extension = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass(myUTI, kUTTagClassFilenameExtension);
Algid answered 10/5, 2012 at 17:27 Comment(2)
Very cool. I've not tested it yet because I have an extra question: the class reference says "Translates a uniform type identifier to a list of tags" but the return type is CFStringRef... Shouldn't it be CFArrayRef?Faludi
Definitely true. The documentation is contradictory regarding the return type of the function. You should file a documentation bug. Nevertheless, the function returns a string, not an array.Algid
C
6

Swift 5

import MobileCoreServices

static func fileExtension(for dataUTI: String) -> String? {
    guard let fileExtension = UTTypeCopyPreferredTagWithClass(dataUTI as CFString, kUTTagClassFilenameExtension) else {
        return nil
    }

    return String(fileExtension.takeRetainedValue())
}
Catharina answered 9/3, 2020 at 18:24 Comment(2)
You need to use .takeRetainedValue() instead to avoid a memory leak... see this answer and this more general answer for more information. Also this article has more general info on Swift interactions with Unmanaged return types from C APIs.Brindled
Good catch @justinpawela, thanks for improving my answer. Just edited it based on your factual suggestion.Catharina

© 2022 - 2024 — McMap. All rights reserved.