swiftfiletypesuidocumentpickerviewcontrolleruttype

How to use UTType with a UIDocumentPicker (pages? docx?)


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)
}

Solution

  • 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")