2

I'm trying to open a picker with only certain file types allowed. I'm using this documentation to find the UTTYpe I need: https://developer.apple.com/documentation/uniformtypeidentifiers/uttype/system_declared_uniform_type_identifiers

but I can't find a UTTYpe for .pages, .doc, .docx for example...

what should I do?

this is my code for the moment

    func presentPickerDocument() {
    //Create a picker specifying file type and mode
    var supportedTypes: [UTType]
    supportedTypes = [UTType.pdf, UTType.url]

    let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: supportedTypes, asCopy: true)
    documentPicker.delegate = self
    documentPicker.allowsMultipleSelection = false
    present(documentPicker, animated: true, completion: nil)
}

1 Answers1

9

You can create a UTType from a file extension like this:

UTType(tag: "pages", tagClass: .filenameExtension, conformingTo: nil)

This creates a UTType?, as there can be no UTType associated with the given file extension.

You can also use:

UTType(filenameExtension: "pages")

but this only finds a UTType if the file extension inherits from public.data, so it won't work for all the file extensions.

On macOS Terminal, you can also use the mdls command to inspect the Uniform Type Identifier of a file

mdls -name kMDItemContentType yourFile.pages

Or its entire tree:

mdls -name kMDItemContentTypeTree yourFile.pages

After that you can create a UTType using its identifier like this:

UTType("com.apple.iwork.pages.sffpages")
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Is the tag same as the extension? Where do I get it from for arbitrary extensions? – Amir Hajiha Sep 21 '22 at 07:26
  • 1
    @AmirHajiha There are many tags that a `UTType` may have, grouped into tag classes. One of them is the `.filenameExtension` tag class. See what I passed for the `tagClass` parameter there? I'm getting the `UTType` that has the `filenameExtension` tag class tag of `pages` associated with it. – Sweeper Sep 21 '22 at 07:45
  • @AmirHajiha So basically to answer your question, *yes*, as long as you do `tagClass: .filenameExtension`. If it can't get it from an extension, you can always use the method in the second half of the answer to view the UTType of a particular file. – Sweeper Sep 21 '22 at 07:47
  • There seems to be UTType.CreateFromExtension introduced in iOS 14 upwards so I will try that as well in my Xamarin.iOS project – Amir Hajiha Sep 21 '22 at 07:53
  • 1
    @AmirHajiha Not very familiar with Xamarin, but I *think* that is the Xamarin.iOS version of `UTType(filenameExtension: "pages")` (my second code snippet). – Sweeper Sep 21 '22 at 08:00