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

user732274
  • 1,069
  • 1
  • 12
  • 28

2 Answers2

11

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

NSString *extension = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass(myUTI, kUTTagClassFilenameExtension);
Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • 1
    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? – user732274 May 10 '12 at 17:33
  • 1
    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. – Nikolai Ruhe May 10 '12 at 17:45
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())
}
om-ha
  • 3,102
  • 24
  • 37
  • 3
    You need to use `.takeRetainedValue()` instead to avoid a memory leak... see [this answer](https://stackoverflow.com/a/26635805/2194039) and [this more general answer](https://stackoverflow.com/a/29049072/2194039) for more information. Also [this article](https://nshipster.com/unmanaged/) has more general info on Swift interactions with `Unmanaged` return types from C APIs. – justinpawela Apr 24 '20 at 20:17
  • Good catch @justinpawela, thanks for improving my answer. Just edited it based on your factual suggestion. – om-ha May 05 '20 at 22:13